Mysql regexp在预备语句中的问题


mysql regexp in prepared statement trouble

我正在为一个网站制作一个基于类别的过滤系统。这些类别与数据库中的每条内容一起保存。类别为整型。

我可以直接查询数据库,这给了我想要的结果。

mysql> select id, name, category, url, price from content where category REGEXP '1|2|3|4|5|6';

这返回

+----+------------+----------+--------------------------+-------+
| id | name       | category | url                      | price |
+----+------------+----------+--------------------------+-------+
|  1 | landschap1 |        2 | Ideal-landscape.jpg      |    20 |
|  2 | landschap1 |        2 | landscape-Photograps.jpg |    20 |
|  4 | landschap1 |        2 | landscape.jpg            |    25 |
|  5 | bunny      |        4 | bunny.mov                |   100 |
+----+------------+----------+--------------------------+-------+
然而,当在php中尝试

时,我得到语法错误或访问冲突。由于代码所使用的数据库用户没有丢失权限,因此这一定是语法错误。

我要执行的查询:

if(empty($_SESSION['filter'])){
    $halfFilt = array(1,2,3,4,5,6);
$filter = implode('|', $halfFilt);
//If filter halfFilt is empty, assume no filter is selected.
$sql = "SELECT * FROM content WHERE id=:id AND WHERE category REGEXP :filter";
$sth->bindParam(':id', $id, PDO::PARAM_INT);
$sth->bindParam(':filter', $filter);
$sth->execute();
$results = $sth->fetch(PDO::FETCH_ASSOC);
return $results;

当我尝试执行这个查询时,它抛出的错误是:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE category REGEXP '1|2|3|4|5|6'' at line 1' in /var/www/portfolio/photoshop/include/database.php:89

问题与正则表达式无关。您不小心在查询中添加了额外的WHERE。像这样替换它,它应该可以工作:

$sql = "SELECT * FROM content WHERE id=:id AND category REGEXP :filter";