0

说到 php 和 mysql,我必须说我还是个婴儿,但是在你们的帮助下,我每天都在学习和提高。是的,我使用 MySQL 在 PHP 中创建了一个搜索引擎,并且在某种程度上,它正在工作,但面临的挑战是,PDOException当我使用多个关键字(如“David Smith”但使用“David”)进行搜索时,我会收到错误消息或“史密斯”单独,我没有得到任何错误。

老实说,我不知道我在哪里弄错了。我正在为我的数据库使用 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)); 

就像我说的,当我使用像“大卫”这样的单个关键字进行搜索时效果很好,但是当我使用像“大卫史密斯”这样的关键字进行搜索时会出错。

以下是我收到的错误消息:

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)); 
4

2 回答 2

0

放个空格

$construct .="AND Use

在 AND 前面是这样的:

$construct .=" AND Use
于 2013-08-23T11:13:42.307 回答
0

尝试使用数组,然后将其内爆:-

//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));
于 2013-07-07T21:58:41.797 回答