Saturday, 27 June 2015

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);
}

0 comments:

Post a Comment