我根据类别为网上商店制作过滤系统。这些类别与数据库中的每个内容一起保存。这些类别是整数。
我能够直接查询数据库,这给了我想要的结果。
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
答案 0 :(得分:1)
问题与正则表达式无关。您不小心在查询中添加了额外的WHERE
。像这样替换它应该有希望工作:
$sql = "SELECT * FROM content WHERE id=:id AND category REGEXP :filter";