语言:PHP 和 MySQL
我在数据库中有一些行具有值为 NULL 的列。我有一个函数可以在收到 $params 数组时构建查询。这是该函数中的相关代码(用于构建 WHERE 子句):
if (isset($params['where'])) {
$query .= "WHERE ";
$count = count($params['where']);
foreach ($params['where'] as $key => $value) {
$count--;
if ($count) {
$query .= "`$key` ".$value['sign']." '".$value['text']."' AND ";
} else {
$query .= "`$key` ".$value['sign']." '".$value['text']."' ";
}
}
}
问题是当我将 $value['text'] 设置为 null 时,结果如下:
SELECT * FROM `db_profiles` WHERE `committed` IS '' LIMIT 100
如果我将它设置为 $value['text'] = 'NULL',那么我会得到以下信息:
SELECT * FROM `db_profiles` WHERE `committed` IS 'NULL' LIMIT 100
这当然不会产生任何结果。有任何想法吗?
回答
if (isset($params['where'])) {
$where_segment = array ();
foreach ($params['where'] as $key => $value) {
if (is_null($value['text'])) {
$where_segment[] = "`".$key."`"." IS NULL";
} else {
$where_segment[] = "`$key` ".$value['sign']." '".$value['text']."' ";
}
}
$query .= " WHERE ".implode('AND', $where_segment);
}