COALESCE和str_replace

时间:2015-09-30 16:42:27

标签: php mysql database

我正在使用COALESCE只将表格中的空输入更新到我的sql DB中,一切正常:

$horiz_deux = $_POST["horiz_deux"];
$horiz_gauche = $_POST["horiz_gauche"];
other ones ...

mysql_query("UPDATE inscription SET horiz_deux = COALESCE('$horiz_deux', horiz_deux) WHERE id = $dossard");
mysql_query("UPDATE inscription SET horiz_gauche = COALESCE('$horiz_gauche', horiz_gauche) WHERE id = $dossard");
other updates...

但是当我想要的时候。用

代替
$horiz_deux = str_replace(".", ",",$_POST["horiz_deux"]);

它也会更新所有其他输入。

对此有何想法?

1 个答案:

答案 0 :(得分:1)

我认为这是因为函数http://php.net/manual/en/function.str-replace.php总是返回一个字符串或一个数组。所以$ horiz_gauche的值总是与NULL不同,因此被COALESCE语句选中,导致数据库中horiz_gauche的更新。

您可以尝试在将$ horiz_gauche插入SQL语句之前将其打印出来以确认其内容。

你可以尝试:

$horiz_deux = isset($_POST["horiz_deux"]) ? $_POST["horiz_deux"] : '';
if ($horiz_deux != '')
{
  $horiz_deux = str_replace(".", ",",$horiz_deux);
  mysql_query("UPDATE inscription SET horiz_deux = COALESCE('$horiz_deux', horiz_deux) WHERE id = $dossard");
}

这非常麻烦,您可以编写一个迭代所有输入字段的循环并检查它们是否有效输入:

$myFieldNames = array('horiz_deux','horiz_hauche','something_else');
foreach ($myFieldNames as $fieldName)
{
  $value = isset($_POST[$fieldName]) ? $_POST[$fieldName] : '';
  $value = str_replace(".", ",",$value);
  mysql_query("UPDATE inscription SET $fieldName = COALESCE('$value', $fieldName) WHERE id = $dossard");
}