Skip to content

Instantly share code, notes, and snippets.

@hmbilal
Created April 18, 2015 09:19
Show Gist options
  • Save hmbilal/03bccc335f1e11f5814d to your computer and use it in GitHub Desktop.
Save hmbilal/03bccc335f1e11f5814d to your computer and use it in GitHub Desktop.
importing csv file into mysql using php
<?php
define("DB_HOST", "localhost");
define("DB_NAME", "db_name");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("CSV_FILE", "file.csv");
$db = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . "," . DB_USER . "," . DB_PASSWORD);
if (($handle = fopen(CSV_FILE, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { // fgetcsv(file, buffer, delimiter)
// query
$sql = "INSERT INTO mytable (name,email) VALUES (:name,:email)";
$q = $db->prepare($sql);
$q->execute(array(':name'=>$data[0],
':email'=>$data[1]));
}
fclose($handle);
} else {
die("Can't open file " . CSV_FILE);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment