我想只在设置了类型和艺术家专栏时进行搜索。因此,如果其中一个设置为全部'我会宣称他们是“空”'而不是搜索该列。这就是我提出的,但它无法正常工作。
if($genre=='all')
{
$genre=NULL;
}
if($artist=='all')
{
$artist=NULL;
}
$query=$conn->prepare('SELECT * FROM songs WHERE (genre=?) && (artist=?)');
$query->bindValue(1,$genre,PDO::PARAM_STR);
$query->bindValue(2,$artist,PDO::PARAM_STR);
$query->execute();
$array=$query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($array);
答案 0 :(得分:0)
此问题与PDO无关,但与(My)SQL有关。
尝试在查询查询中展开占位符,并参阅:
mysql> select 1=null;
+--------+
| 1=null |
+--------+
| NULL |
+--------+
1 row in set (0.05 sec)
mysql> select 1 && 1=null;
+-------------+
| 1 && 1=null |
+-------------+
| NULL |
+-------------+
1 row in set (0.00 sec)
如果将值与null进行比较,则会得到null 如果在逻辑运算符中使用null,则为null
所以,你需要另一种方式
$params = array();
$where = array();
if($genre && $genre != 'all')
{
$where[] = "(genre=?)";
$params[] = $genre;
}
if($artist && $artist != 'all')
{
$where[] = "(artist=?)";
$params[] = $artist;
}
$sql = 'SELECT * FROM songs';
if ($where) {
$sql .= 'WHERE '.implode('&&', $where);
}
$stm = $conn->prepare($sql);
$stm->execute($params);
echo json_encode($stm->fetchAll(PDO::FETCH_ASSOC));
答案 1 :(得分:0)
尝试遵循:
$where = array();
$preps = array();
if ($genre!=='all') {
$where[] = 'genre = ?';
$preps[] = $genre;
}
if ($artist!=='all') {
$where[] = 'artist = ?';
$preps[] = $artist;
}
$where = $where ? "WHERE ". implode(' AND ', $where) : '';
$query=$conn->prepare('SELECT * FROM songs '.$where);
if($preps) $query->execute($preps);
else $query->execute();
$array=$query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($array);