I am trying to insert data into MySql table from csv file using PHP,
please see this image - my CSV file.
the problem i face is, while loading the CSV file, the net_sales column becomes rounded and inserted in the table.
please see below sample image of MySql Table after inserting.
FYI, here i am showing only net_sales column for explaining my problem, actually i have more columns in the table and CSV.
due to some reasons, i cant have a static insert statement like this "insert into tran_detail (tran_id,tran_datetime,net_sales) values (...)";
so i prefer to have this statement "INSERT INTO tran_detail (".implode(',', array_keys($data)).") VALUES('".implode('\',\'', array_map("convert",array_values($data)))."')";
this is the PHP i am using for inserting. please help to insert the value with decimals in table as it is in the CSV.
function convert($string)
{
return htmlspecialchars($string,ENT_QUOTES);
}
$columnArray = array();
$dataArray = array();
$firstRule = true;
while ($data = fgetcsv ($source, 1000, ","))
{
if($firstRule)
{
foreach($data as $columnName)
{
$columnArray[] = $columnName;
}
$firstRule = false;
}
else
{
$rule = array();
for($i = 0; $i < count($data) ; $i++)
{
$rule[$columnArray[$i]] = $data[$i];
}
$dataArray[] = $rule;
}
}
foreach($dataArray as $data)
{
$query = "INSERT INTO `tran_detail` (".implode('`,`', array_keys($data))."`) VALUES('".implode('\',\'', array_map("convert",array_values($data)))."')";
mysql_query($query) or mysql_error();
}
fclose($source);
This is the way I would do this:
Note I can only do limited testing on this ( no DB or files ), so for testing and explanation purposes here is the code for testing the basic functionality.
Outputs
You can check it out here.
http://sandbox.onlinephpfunctions.com/code/ab868ac6c6fbf43d74cf62ef2907b0c72e1f59bf
The most important part in the output is the last 2 arrays, as you can see how we map the data to the file headers, and then use the
$default_map
to fill in any missing columns. You can put whatever defaults in there you need, such as null or what have you, but you'll have to do it manually instead of using$default_map = array_fill_keys($placeholders, '');
This should make it pretty self explanatory, if not feel free to ask.
Hopefully I got everything matched up between them and for the DB and file stuff, if not it should be really close. But this is quite a bit of fairly complex code, so it's not inconceivable I may have missed something.
The important thing is this will let you map out the CSV data in an elegant way, and avoid any SQL Injection nastyness.