Tag Archives: CSV

PHP – Import CSV to MySQL

The following code snippet can be used to import CSV into MySQL using PHP.

<?php
$delimiter = ',';

$db = new mysqli('localhost', 'username', 'password', 'database');

if (($handle = fopen("import.csv", "r")) !== FALSE) {
	while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
		foreach($data as $i => $content) {
			$data[$i] = $db->real_escape_string($content);
		}
		$db->query("INSERT INTO mytable VALUES('" . implode("','", $data) . "');");
	}
	fclose($handle);
}

?>

A few things to keep in mind:

  • Make sure you change the MySQL login information to your own login information
  • Make sure you change the table name, in this case, mytable, to your own table name.
  • For your CSV (comma separated values) file, the delimiter may not necessarily be a comma. Change the $delimiter variable to the one-character delimiter separating the different fields.
  • This does NOT automatically create a table. You have to manually do that.
  • Every row would be inserted, so you should manually remove the first row if it is just the column names.