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.

2 thoughts on “PHP – Import CSV to MySQL

  1. Mauricio Torrejon

    I read your post and I was wondering if there is a way to create the table with as many rows as many columns the csv file has. Pretty much import a csv file and dynamically create the table so it fits the file being imported. Thanks in advance

    Reply
    1. Tech163 Post author

      Definitely possible. You should check the mysql documentations for SQL to create a table.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>