Skip to content

Instantly share code, notes, and snippets.

@gustawdaniel
Created July 29, 2017 10:20
Show Gist options
  • Save gustawdaniel/421c5d2b46b3309506ab4afe5be90adf to your computer and use it in GitHub Desktop.
Save gustawdaniel/421c5d2b46b3309506ab4afe5be90adf to your computer and use it in GitHub Desktop.
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$database = 'ingrid';
$file = 'ABBREV.csv';
$db = new PDO("mysql:dbname=".$database.";host=".$host, $user, $pass);
/********************************************************************************/
// Parameters: filename.csv table_name
$table = pathinfo($file);
$table = $table['filename'];
/********************************************************************************/
// Get the first row to create the column headings
$fp = fopen($file, 'r');
$frow = fgetcsv($fp);
$columns = null;
foreach($frow as $column) {
if($columns) $columns .= ', ';
$columns .= "`$column` varchar(250)";
}
$create = "create table if not exists $table ($columns);";
$db->query($create)->execute();
/********************************************************************************/
// Import the data into the newly created table.
$file = $_SERVER['PWD'].'/'.$file;
$q = "load data infile '$file' into table $table fields terminated by ',' ignore 1 lines";
$db->query($q)->execute();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment