Php 仅更新非空记录

Php 仅更新非空记录,php,mysql,Php,Mysql,我有这个查询,我用它来更新一个表。 问题是,我只需要更新与“未定义”不同的值 在这里有人的帮助下,我得到了这个问题: $sqlStart="UPDATE forma SET "; $sql=""; if (!empty($postDyqani_pergjegjes)) $sql += " dyqani_pergjegjes='$postDyqani_pergjegjes',"; if (!empty($postEmri)) $sql += " emri='$postEmri',"; if (!

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

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

$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 {
}
但它不会执行。。 请帮我一把。。 如果我打印变量,大多数结果都是
未定义的

谢谢

你的方法让很多事情都失败了;首先,+=不会像您认为的那样处理PHP字符串,并且可能会使所有内容都以值0结束。使用.=将字符串连接到现有字符串:

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

// $foo == '123abc'
第二,如果没有更多关于变量来源的信息,就很难说什么是错误的。如果您有一个名为“Dyqani_pergjes”的字段,正确的引用方式是使用
$\u POST['Dyqani_pergjes']

此外,如果要正确解决SQL查询中要使用的字符串,还需要对其进行转义,以避免SQL注入漏洞攻击和其他可能的错误(或者在mysqli中使用准备好的语句或使用PDO):


您还缺少UPDATE语句的条件,因此在它的当前形式中,它将更改数据库中的所有行。可能不是你想要的。并且您不需要在语句末尾添加“;”—这在执行查询时是隐含的,通常建议不要使用“;”。

未定义“?PHP或MySQL中没有这样的值。请描述一下你想做得更好的地方。也许
。。。如果某个变量不为NULL
?其思想是,更新查询将是flexibele,因此某些变量即使在查询中,也可能没有值,当我打印它们时,它会显示unfinedcan u do echo$sqlStart;出口在“如果”之前给我看我做到了。。但是我什么都没有..你有没有试着把用于加法的
+=
改成@Kao所指出的用于字符串连接的
=
difekti='". mysql_real_escape_string($postDifekti) . "'