Created
February 3, 2015 15:39
-
-
Save georgioupanayiotis/4a74b9692fc3194fd993 to your computer and use it in GitHub Desktop.
Import data to websites is an important functionality, So in this tutorial will show you how to import CSV data to table with PHP.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Database configs | |
$host="localhost"; | |
$dbuser=""; | |
$dbpass=""; | |
$dbname = ""; | |
$link = mysqli_connect($host, $dbuser, $dbpass, $dbname); | |
if (mysqli_connect_errno()) | |
echo mysqli_connect_error(); | |
//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: | |
$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!"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment