Import CSV data to table with PHP



As Import and Export is an important functionality of a website and we have already discussed about how to Export data to CSV file in php. So in this tutorial I will show you how to import CSV data to table with PHP.

First we need to read the CSV file using fopen function like below:

$csv_file = "sample_table.csv";
$csvfile = fopen($csv_file, 'r');

Now to get row from CSV file we need to useĀ fgetcsv function like below:

$data = fgetcsv($csvfile, 1024, ",");

So the complete code for import simple CSV file is as follow:

// Database configs
$host="localhost";
$dbuser="root";
$dbpass="";
$dbname = "dummydb";

$link = mysqli_connect($host, $dbuser, $dbpass, $dbname);

if (mysqli_connect_errno())
	echo mysqli_connect_error();

$csv_file = "sample_table.csv"; // CSV file to import
$csvfile = fopen($csv_file, 'r');

$i = 0;
while (($data = fgetcsv($csvfile, 1024, ",")) !== FALSE) {
	if($i==0) { $i++; continue; }  // to exclude first row in the csv file.

	$id = $data[0];  		// first field
	$title = $data[1]; 		// second field
	$description = $data[2]; 	// third field

	$query = "INSERT INTO sample_table SET id = '".$id."', title = '".$title."', description = '".$description."' ";

	mysqli_query($link, $query);
}
fclose($csvfile);

echo "CSV data imported successfully!";

This is a simple code to import CSV data to table with PHP. Hope this will help you.