Build Table from File PHP Function

This is post is now quite old and the the information it contains may be out of date or innacurate.

If you find any errors or have any suggestions to update the information please let us know or create a pull request on GitHub

This little PHP function will allow you to import a csv or tab etc delimited text file into a database table. Handy if you need it :)

function build_table_from_file($tablename, $filepath, $delim="\t") {
    db_query("DROP TABLE IF EXISTS $tablename");
    $fp=fopen($filepath, 'r');
    $headers=false;
    while($r=(($delim=='csv')?fgetcsv($fp):fgets($fp))) {
        if($delim!='csv'){
            $r=explode($delim, $r);
        }
        if(!$headers) {
            foreach($r as $h){
                $headers[]=trim($h);
            }
            $sql = "CREATE TABLE $tablename
                         (
                            `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,";
            foreach($headers as $h) {
                $sqls[]=" `" . db_in($h) . "` TEXT NOT NULL ";
            }
            $sql .= implode(', ', $sqls) . "
                        ) ENGINE = MYISAM ";
            db_query($sql);
            continue;
        }
        $sql = "insert into $tablename set ";
        $sqls=array();
        foreach($headers as $k=>$h) {
            $sqls[] = "`$h` = '" . db_in($r[$k]) . "'";
        }
        $sql .= implode(', ', $sqls);
        db_query($sql);
        pbar();
    }
}

Tags: phptablefileimportcsv