[英]Search engine in PHP with MySQL: Unable to search with more than a single keyword, gives PDOException Error
I must say am still a baby when it comes to php and mysql, but am learning and improving everyday with you guys help. 我必须说,在涉及php和mysql时,我还是一个婴儿,但是每天都在你们的帮助下学习和改进。 Yeah I created a search engine in PHP with MySQL and to an extent, it is working, but the challenge that am having is that I get
PDOException
error message when i search with more than a single keyword like 'David Smith' but with 'David' or 'Smith' alone, i don't get any error. 是的,我在MySQL中使用MySQL创建了一个搜索引擎,并且在一定程度上可以正常工作,但是所面临的挑战是,当我使用多个单词(例如“ David Smith”)而不是“ David”进行搜索时,会收到
PDOException
错误消息或“史密斯”一个字,我没有收到任何错误。
Honestly I don't know where I got it all wrong. 老实说,我不知道我在哪里弄错了。 Am using wampserver
PDO db connection
for my Database. 我正在为我的数据库使用wampserver
PDO db connection
。 below is the sample of the code. 下面是代码示例。
//search button name and id is 'search'
$search_exploded = explode (" ", $search);
foreach($search_exploded as $search_each)
{
for($x=0; $x<=0; $x++ );
if($x==1)
$construct .="UserID LIKE '%$search_each%' or Requestor LIKE '%$search_each%' or EmploymentType LIKE '%$search_each%'";
else
$construct .="AND UserID LIKE '%$search_each%' AND Requestor LIKE '%$search_each%' AND EmploymentType LIKE '%$search_each%'";
}
$sql = "SELECT COUNT(*) as num FROM ".TBL_STUDENTS." WHERE $construct";
$result = $database->connection->prepare($sql);
$result->execute(array($construct));
Like i said, it works fine when i search with a single keyword like 'David' but i get error when i search with something like 'David Smith'. 就像我说的那样,当我使用“ David”之类的单个关键字进行搜索时,效果很好,但是当我使用“ David Smith”之类的内容进行搜索时却出现错误。
Below is the error message that I do get: 以下是我得到的错误消息:
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 'UserID LIKE '%Gift%' or Requestor LIKE `%Gift%` or EmploymentType LIKE `%Gift%` at line 3'
in `C:\wamp\www\ccnl\script\search_db.php` on line 108
The line is this code below 该行是下面的代码
$result->execute(array($construct));
Try using an array, then imploding it:- 尝试使用一个数组,然后分解它:-
//search button name and id is 'search'
$search_exploded = explode (" ", $search);
$construct = array();
foreach($search_exploded as $search_each)
{
$construct[] =" (UserID LIKE '%$search_each%' or Requestor LIKE '%$search_each%' or EmploymentType LIKE '%$search_each%') ";
}
$sql = "SELECT COUNT(*) as num FROM ".TBL_STUDENTS." WHERE ".implode(" OR ", $construct);
$result = $database->connection->prepare($sql);
$result->execute(array($construct));
Put a space 放一个空间
$construct .="AND Use
in front of AND like this: 在AND前面,如下所示:
$construct .=" AND Use
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.