我必须说,在 php 和 mysql 方面我还是个婴儿,但在你们的帮助下我每天都在学习和进步。
是的,我用 PHP 和 MySQL 创建了一个搜索引擎,在某种程度上,它正在工作,但我面临的挑战是,当我使用多个关键字(如“”)进行搜索时,我会收到 PDOException
错误消息David Smith”,但单独使用“David”或“Smith”时,我不会收到任何错误。
老实说,我不知道我哪里错了。我的数据库使用 wampserver PDO db 连接
。下面是代码示例。
//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));
关于php - PHP 和 MySQL : Unable to search with more than a single keyword, 中的搜索引擎给出 PDOException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17516712/