【问题标题】:sql select where like statement with many OR operands带有许多 OR 操作数的 sql select where like 语句
【发布时间】:2014-05-22 07:19:30
【问题描述】:

我正在尝试编写一个读取字符串 $query 的简单搜索函数。

我的问题是,我可以在一个 select 语句中使用多个 OR 吗?我正在尝试搜索一个字符串以查看它是否与许多列值匹配,然后打印这些行。

function search($query) {
   try {
     $db = db_open();

     $sql = "select * from pms where (name like :query) or (state like :query) or 
             (start like :query) or (finish like :query) ";

     $statement = $db->prepare($sql);
     $statement->bindValue(':query', $query);
     $statement->execute();
     $pms = $statement->fetchAll();

   } catch(PDOException $e) {
     die("Error: ".$e->getMessage());
     }
   return $pms;
   }

这不起作用,除非我搜索状态。

谢谢

【问题讨论】:

  • 已解决,绑定语句中的语法不正确。 $statement->bindValue(':query', $query); 应该是:$statement->bindValue(':query', "%$query%"); 感谢其他成员的建议。无论如何,他们帮助整理了我的代码:-)

标签: php select sqlite where sql-like


【解决方案1】:

当然。

SELECT * FROM pms WHERE (name LIKE :query) OR (start LIKE :query) OR (finish LIKE :query)

应该可以正常工作。

【讨论】:

  • 不,这不起作用:-(。仍然只有状态在工作。我会发布整个功能,也许我还有其他问题。
【解决方案2】:

1) 在表名和列名中使用反引号。
2)为每个或更清晰的理解使用括号
3)如果您不使用绑定,则使用带引号的通配符(%)。 试试这样:

$sql = "select * from `pms` 
where (`name` like '%query%') 
OR (`state` like '%query%') 
OR (`start` like '%query%') 
OR  (`finish` like '%query%') ";

【讨论】:

  • 感谢您的回复。这仍然没有用。它仅在我使用时有效:$sql = "select * from pms where name like '%$query%' or state like '%$query%' or start like '%$query%' or finish like '%$query%'";
  • 我以为您正在绑定您的查询。好的,我正在更新我的答案。如果有帮助,那么您应该接受我的回答:)
猜你喜欢
  • 2018-03-08
  • 2014-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
  • 1970-01-01
  • 2016-04-26
相关资源
最近更新 更多