我将数据从exel放入数据库(Mysql价格十进制(9,2))。
如何删除空格,逗号(替换为点“。”) 在插入到数据库之前?
在将数据(价格)插入数据库后,我有1.00,我应该有1235.00
Exel文件->; 价格
1 456,34
1 350,21
1 200,00
1 235,23
300,14
350,00
345,00
436,00
436,00
php文件
foreach($data as $row)
{
$price = str_replace(' ', '', ':price');
$price = str_replace(',', '.', $price);
$price = preg_replace('/\s+/', '', $price);
$insert_data = array(
':sym_id' => $row[0],
':code' => $row[1],
':name' => $row[2],
':quantity' => $row[3],
':price' => $row[4],
':position' => $row[5],
':visible' => $row[6]
);
$query = "
INSERT INTO symphony
(sym_id, code, name, quantity, price, position, visible)
VALUES (:sym_id, :code, :name, :quantity, $price, :position, :visible)
";
$statement = $connect->prepare($query);
$statement->execute($insert_data);
}
首先,我不知道你在期待什么:
$price = str_replace(' ', '', ':price');
$price = preg_replace('/\s+/', '', $price);
去做。 但最终发生的情况是,您有一个名为$price
的变量,它填充了值':price'
。 我怀疑它的计算结果为true
,导致MySQL将1.00放入十进制字段。
我想你是想用小数点代替逗号来结束价格。 这将更接近:
foreach($data as $row)
{
//Remove the price conversion. It did nothing
$insert_data = array(
':sym_id' => $row[0],
':code' => $row[1],
':name' => $row[2],
':quantity' => $row[3],
':price' => preg_replace('/,/', '.', $row[4]), //Replace you're comma with a point
':position' => $row[5],
':visible' => $row[6]
);
//Use only named values here. Don't put the variable '$price' in here at all
$query = "
INSERT INTO symphony
(sym_id, code, name, quantity, price, position, visible)
VALUES (:sym_id, :code, :name, :quantity, :price, :position, :visible)
";
$statement = $connect->prepare($query);
//Use insert data to fill the named parameters
$statement->execute($insert_data);
}
但是等等。。。 如果用户同时使用.
作为千分隔符,使用,
作为十进制分隔符,会发生什么情况。 那么您需要更进一步,使用PHP的数字格式化程序。 详情请访问:https://www.php.net/manual/en/numberformatter.parse.php
编辑:
我看到自从我开始写答案以来,你稍微改变了循环中的行:
$price = str_replace(' ', '', ':price');
$price = str_replace(',', '.', $price);
$price = preg_replace('/\s+/', '', $price);
但是,效果仍然是一样的:在这些行的末尾,$price
===':price'
。 str_replace
的第三个参数是这些行更改的字符串,它既不包含逗号也不包含空格。