仅更新非空的记录

时间:2012-12-12 08:11:16

标签: php mysql

我有这个查询,我用它来更新表。 问题是,我只需要更新与“undefined”不同的值

在这里的某人的帮助下,我得到了这个问题:

$sqlStart="UPDATE forma SET ";
$sql="";
if (!empty($postDyqani_pergjegjes)) $sql += " dyqani_pergjegjes='$postDyqani_pergjegjes',";
if (!empty($postEmri)) $sql += "  emri='$postEmri',";
if (!empty($postKlienti)) $sql += "  klienti='$postKlienti',";
if (!empty($postTelefoni)) $sql += "  telefoni='$postTelefoni,'";
if (!empty($postMontim)) $sql += "  montim='$postMontim',";
if (!empty($postAdresa)) $sql += "  adresa='$postAdresa',";
if (!empty($postData_e_shitjes)) $sql += "  data_e_shitjes='$postData_e_shitjes',";
if (!empty($postDifekti)) $sql += "  difekti='$postDifekti',";
if (!empty($postTekniku_emer)) $sql += "  tekniku_emer='$postTekniku_emer',";
if (!empty($postTekniku_mesazh)) $sql += "  tekniku_mesazh='$postTekniku_mesazh',";
if (!empty($postData_fillim)) $sql += "  data_fillim='$postData_fillim',";
if (!empty($postData_mbarim)) $sql += "  data_mbarim='$postData_mbarim',";
if (!empty($postData)) $sql += "  data='$postData',";
if (!empty($postStatus)) $sql += "  status='$postStatus',";
// replace the last `,` for `;`
if ($sql != "") {
$sql = substr($sql, 0, -1) . ";";

    // replace the last `,` for `;`
    // run sql command
    echo $sqlCommand = $sqlStart.$sql;
    $result=mysql_query($sqlCommand) or die(mysql_error()) ;

} else {
}

虽然不会执行.. 请帮我一把.. 如果我打印变量,其中大部分变为undefined 感谢

1 个答案:

答案 0 :(得分:0)

你的方法有很多坏事;首先,+ =不会做你认为它对PHP字符串做的事情,并且可能会使所有内容最终成为值0.使用。=将字符串连接到现有字符串:

$foo = '123';
$foo .= 'abc';

// $foo == '123abc'

其次,如果没有关于变量来自何处的更多信息,很难说出错误的方式。如果你有一个名为'Dyqani_pergjegjes'的字段,引用它的正确方法是使用$_POST['Dyqani_pergjegjes']

此外,您需要转义要在SQL查询中使用的字符串,以避免SQL注入攻击和其他可能的错误(或者在mysqli中使用预处理语句或使用PDO),如果您想要正确解决它:

difekti='". mysql_real_escape_string($postDifekti) . "'

你也错过了UPDATE语句的条件,所以在它的当前形式中它将改变数据库中的所有行。可能不是你想要的。而且你不需要添加“;”在语句的末尾 - 这在执行查询时是隐含的,通常建议不要使用。

相关问题