php - 仅当该值不同于空值时才更新列上的值

标签 php mysql

我有这个表格,现在,我只需要用不为空的变量更新数据库的部分。 我的意思是,如果我有这个:

$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, $postKlientiundefinedempty,我不希望更新该记录。 我怎样才能使用某些条件来做到这一点?

谢谢

所以我需要这样做?

$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/

相关文章:

php - php mysql 比较之前的请求值和当前值

php - 从数据库检索的网络表中删除行

javascript - 当谷歌地图标记移动时更新mysql数据库

mysql - SQL Query Select 基于 Group By 的条件

php - 在 PHP 中从线性数组创建关联数组

php - 我在使用 PHP 将变量从 SQL 解析为另一个 SQL 语句时遇到问题

javascript - PHP FTP 上传 BLOB TEMP 图像

mysql - 返回 mySQL 原始行号

php - 我想在循环获取的行时创建二维数组

PHP 拆分逗号分隔值但保留引号