EDITED: For change of code and issue...
I've been testing the following code and working to modify it for a small project I have...
Works great except for one thing...
If the CSV file has less delimited data than there are columns in the table I get the SQL error: Column count doesn't match value count at row "x"
Is there any way to input a 0 for the missing data sets?
I've done the same import using phpMyAdmin and had the correct results stored...
Any advice is welcomed...
// Database server host
$sql_db['host'] = "localhost";
// Database name
$sql_db['name'] = "test";
// Database user name
$sql_db['user'] = "root";
// Database password
$sql_db['pass'] = "";
// Database table name
$sql_db['tble'] = "mydata";
// Absolute path or URL (e.g. http://...) to the CSV file
$csv_file['path'] = "/path/to/csvfile/csvdata.csv";
// Value Separator used in CSV file
$csv_file['sepa'] = ";";
// ======================================================================
// Connect to MySQL database
// ======================================================================
$connect = @mysql_connect($sql_db['host'], $sql_db['user'], $sql_db['pass'])
or die(mysql_error());
$db = @mysql_select_db($sql_db['name'], $connect)
or die(mysql_error());
// ======================================================================
// Create the SQL Insert Query
// ======================================================================
$file_contents_line = @file($csv_file['path'])
or die ("CSV file not found.");
foreach ($file_contents_line as $key => $val)
{
// Skip empty lines
if (empty($val)) continue;
$inserts .= (($key >= 1) ? ", " : "")."('";
$values = explode($csv_file['sepa'], $val);
for ($j = 0; $j < count($values); $j++)
{
$inserts .= addslashes(utf8_decode($values[$j])).(($j != (count($values) - 1)) ? "', '" : "");
}
$inserts .= "')";
}
// ======================================================================
// Store all data into our database
// ======================================================================
$sql = "INSERT INTO ".$sql_db['tble']."
VALUES ".$inserts;
$res = mysql_query($sql)
or die(mysql_error());
echo "Convert successful.\n";