php - PHP 和 MySQL : Unable to search with more than a single keyword, 中的搜索引擎给出 PDOException 错误

标签 php mysql search search-engine

我必须说,在 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/

相关文章:

php - 如何在 PHP 中获取完整的引荐来源网址

php - 更新 JS Var 更改 php var

php - 正则表达式使用逗号 (,) 分隔符拆分字符串,但如果逗号在大括号 {,} 中则忽略

php - 在单独的关键字表中搜索最匹配的 id

Python:只有文件名(而不是路径)可用时如何在系统范围内搜索文件

linux - 将 PHP 框架放在 Linux 主机上的什么位置

mysql - 从查询结果中计算不同的值

php - ActionScript 错误 - 1086 : expecting a semicolon before left curly brace?

mysql - 不重启修改mysql系统变量

git - 为什么git搜索找不到字符串