从CSV文件更新Mysql表

时间:2013-04-26 09:35:50

标签: php mysql

您好我正在尝试从csv文件更新我的MYSQL数据库中的表testprod。 (我在这里找到了代码并根据我的需要更新了它,差不多:))

它更新但十进制值被截断并且在(。)之后它丢失任何信息,例如400.25被减少到400

这是csv文件的示例

'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',

这是php代码。

<?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);

?>

1 个答案:

答案 0 :(得分:5)

将其数据类型设置为DECIMAL(20,5)DOUBLE(20,5)

修改

使用此查询

$query = "UPDATE testprod SET price ='$price' , stock = $stock
WHERE Product_ID = '$Product_ID'";