如果某些列为空,则删除行

时间:2016-05-06 10:36:43

标签: php mysql

我的数据库中有一个动态表,列被更改并从其他脚本中删除。因为有可能所有这些额外的列可能保留空值或空值,最终我想要进行清理'检查那些单元格的某个动作,如果全部为空,则删除整行。

enter image description here

红色的那些是我要检查的。如果两个列都为null或为空,则WHERE customers_id = 1,则删除行。

就像我说的这只是一个例子......在customers_id之后可能有5或10列。如果它们是空的,我需要检查它们。 我可以在这样的字符串中获取这些额外列的所有名称:

$temparray = array();
$q = mydb_query("SHOW COLUMNS FROM $table WHERE field NOT REGEXP 'id|customers_id'");
while($row = mydb_fetch_array($q)){
  $temparray[] = $row['Field'];
}
$forSQL = " '".implode("', '", $temparray)."' ";  // gives  'client_custom_contact_person', 'client_custom_password'
$forPHP = implode(", ", $temparray); //gives   client_custom_contact_person, client_custom_password

检查所有这些列值是否为空以删除该行的最快方法是什么?

我应该使用php foreach函数吗?或者我可以做一个更快的mysql查询?

-Thanks

1 个答案:

答案 0 :(得分:0)

想出来。使用$ forPHP字符串:

$q2 = mydb_query("SELECT $forPHP FROM $table WHERE customers_id = 1");
            $res = mydb_fetch_assoc($q2);
            if(!array_filter($res)) {
                //If all are empty then
                mydb_query("DELETE FROM $table WHERE customers_id = 1");
            }
相关问题