说到php和mysql,我必须说我还是个婴儿,但在你们的帮助下,我每天都在学习和改进。是的,我用MySQL在PHP中创建了一个搜索引擎,在某种程度上,它是有效的,但我面临的挑战是,当我使用多个关键字(如"David Smith")进行搜索时,我会收到PDOException
错误消息,但仅使用"David"或"Smith",我不会收到任何错误。
老实说,我不知道我哪里搞错了。我的数据库正在使用wampserver PDO db connection
。下面是代码示例。
//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));
就像我说的,当我用一个像"David"这样的关键词搜索时,它很好,但当我用像"David Smith"这样的词搜索时,我会出错。
下面是我得到的错误消息:
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
这行是下面的代码
$result->execute(array($construct));
尝试使用数组,然后内爆它:-
//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));
放置一个空格
$construct .="AND Use
在AND前面,如下所示:
$construct .=" AND Use