Hi Im trying to update a table testprod in my MYSQL db from a csv file. (I found the code on here and have updated it to my needs, well nearly :))
It updates but the decimal value is truncated and it loses any info after the (.) eg 400.25 is cut down to 400
here is an sample of the csv file
'Product_ID','Model','HighPic','ManuId','Model_Name','categories_id','categories_image','parent_id','sort_order','categories_name','categories_description','categories_keywords','Name','Image','Price','Supplier','Weight','Stock','datetime'
2055332,,,,,,,,,,,,,,800.4,,,'1',
3916211,,,,,,,,,,,,,,444,,,'15',
12073922,,,,,,,,,,,,,,737.6215,,,'0',
4593772,,,,,,,,,,,,,,2822.4,,,'4',
1684786,,,,,,,,,,,,,,4333.2,,,'1',
and here is the php code.
<?php
// set local variables
$connect = mysql_connect("localhost","db","password") or die('Could not connect: ' . mysql_error());
$handle = fopen("dailyupdates.csv", "r");
// connect to mysql and select database or exit
mysql_select_db("rapido_creloaded", $connect);
// loop content of csv file, using comma as delimiter
while (($data = fgetcsv($handle, 1000, ",")) !== false) {
$Product_ID = $data[0];
$price = $data[14];
$stock = $data[17];
$query = 'SELECT Product_ID FROM testprod';
if (!$result = mysql_query($query)) {
continue;
}
if ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
// entry exists update
$query = "UPDATE testprod SET price ='$price' , stock = '$stock'
WHERE Product_ID = '$Product_ID'";
mysql_query($query);
if (mysql_affected_rows() <= 0) {
// no rows where affected by update query
}
} else {
// entry doesn't exist continue or insert...
}
mysql_free_result($result);
}
fclose($handle);
mysql_close($connect);
?>
In the Format list, select CSV. Changing format-specific options. If the csv file is delimited by a character other than a comma or if there are other specifications to the csv files, we can change it in this portion. Click Go to start importing the csv file and the data will be successfully imported into MySQL.
Importing CSV file using MySQL Workbench The following are steps that you want to import data into a table: Open table to which the data is loaded. Review the data, click Apply button. MySQL workbench will display a dialog “Apply SQL Script to Database”, click Apply button to insert data into the table.
SET its datatype to DECIMAL(20,5)
OR DOUBLE(20,5)
Edit
Use this query
$query = "UPDATE testprod SET price ='$price' , stock = $stock
WHERE Product_ID = '$Product_ID'";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With