Our blog

 

Build Table from File PHP Function

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 :)

PHP:
  1. function build_table_from_file($tablename, $filepath, $delim="\t") {
  2.     db_query("DROP TABLE IF EXISTS $tablename");
  3.     $fp=fopen($filepath, 'r');
  4.     $headers=false;
  5.     while($r=(($delim=='csv')?fgetcsv($fp):fgets($fp))) {
  6.         if($delim!='csv'){
  7.             $r=explode($delim, $r);
  8.         }
  9.         if(!$headers) {
  10.             foreach($r as $h){
  11.                 $headers[]=trim($h);
  12.             }
  13.             $sql = "CREATE TABLE $tablename
  14.                          (
  15.                             `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,";
  16.             foreach($headers as $h) {
  17.                 $sqls[]=" `" . db_in($h) . "` TEXT NOT NULL ";
  18.             }
  19.             $sql .= implode(', ', $sqls) . "
  20.                         ) ENGINE = MYISAM ";
  21.             db_query($sql);
  22.             continue;
  23.         }
  24.         $sql = "insert into $tablename set ";
  25.         $sqls=array();
  26.         foreach($headers as $k=>$h) {
  27.             $sqls[] = "`$h` = '" . db_in($r[$k]) . "'";
  28.         }
  29.         $sql .= implode(', ', $sqls);
  30.         db_query($sql);
  31.         pbar();
  32.     }
  33. }

More Reading:

 

Leave a Reply