Hello people I have a csv file which is having records, I have created table as per the comma seperated values. How can i insert data from csv file to the mysql table? Is there any easiest way?
You can import csv file to the mysql using phpmyadmin or you can do it like following command on mysql prompt load data local infile "filename.csv" into table yourtable fields terminated by ',' enclosed by ' " ' lines terminated by '\n' (fieldname1,fieldname2....)
If you have to import it to PHP without phpMyAdmin (for the love of God please just use phpMyAdmin) and you know the fields, you can make use of the PHP CSV library. Here's a code I wrote a while ago that allows you to import CSV data: if (file_exists($file)) { $csvdb = fopen($file, "r"); } else { $error = "No file was uploaded."; die(); } $i = -1; // Skip first rows - header $valuesbit = ""; $rows = array(); while (($row = fgetcsv($csvdb)) !== false) { $i++; if ($i == 0) { // Don't care about header row continue; } // Data cleaning $somefield = mysql_real_escape_string($row[0]) // The column it is in for this row, a 1D array $another = mysql_real_escape_string($row[1]) $valuesbit .= "('{$somefield}', '{$another}', '{$blah}', {$welp}, {$stuff}, {$happens}),"; } $valuesbit = mb_substr($valuesbit, 0, -1); // Hack $q = mysql_query("INSERT INTO sometable (somefield, another, blah, welp, stuff, happens) VALUES " . $valuesbit); if (!$q) { $error = "A database error occured. Please try again later."; } else { echo ("Success!"); } fclose($csvdb); PHP: