我有这个表格,现在,我只需要用不为空的变量更新数据库的部分。 我的意思是,如果我有这个:
$postEmri = filter_var($_POST["postEmri"], FILTER_SANITIZE_EMAIL);
$postKlienti = filter_var($_POST["postKlienti"], FILTER_SANITIZE_STRING);
$postTelefoni = filter_var($_POST["postTelefoni"], FILTER_SANITIZE_STRING);
还有这个:
$sql="UPDATE forma SET emri='$postEmri', klienti='$postKlienti', telefoni='$postTelefoni'";
如果 $postEmri, $postKlienti
是 undefined
或 empty
,我不希望更新该记录。
我怎样才能使用某些条件来做到这一点?
谢谢
所以我需要这样做?
$sql="UPDATE forma SET ";
// add every non-empty field to the query
if (!empty($postEmri)) $sql += " emri='$postEmri',";
if (!empty($postKlienti)) $sql += " klienti='$postKlienti',";
if (!empty($postTelefoni)) $sql += " telefoni='$postTelefoni,'";
// replace the last `,` for `;`
$sql = substr($sql, 0, -1) . ";";
$result=mysql_query($sql) or die(mysql_error()) ;
最佳答案
如果您只想更新不为空的字段:
$sqlStart="UPDATE forma SET ";
$sql="";
// add every non-empty field to the query
if (!empty($postEmri)) $sql .= " emri='$postEmri',";
if (!empty($postKlienti)) $sql .= " klienti='$postKlienti',";
if (!empty($postTelefoni)) $sql .= " telefoni='$postTelefoni,'";
// if any of the fields is non-empty, run the query
if ($sql != "") {
// replace the last `,` for `;`
$sql = substr($sql, 0, -1) . ";";
// run sql command
$sqlCommand = $sqlStart.$sql;
} else {
// no fields to update
}
关于php - 仅当该值不同于空值时才更新列上的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13822911/