PDO BindParam没有使用Like语句

时间:2015-05-20 23:16:08

标签: php mysql pdo

这是我的代码:

$sch = '%test%';

$select_search_query = "(
        SELECT 
            GROUP_CONCAT(name, ' ', surname) AS result
          FROM users
        WHERE 
        (
            email LIKE :sch OR 
            name LIKE :sch OR 
            surname LIKE :sch
        ) 
        AND 
            id_p = :ff_z
    )";

$prep_search_query = $connection->prepare($select_search_query);

$prep_search_query->bindParam(":sch", $sch);
$prep_search_query->bindParam(":ff_z", $id_p, PDO::PARAM_INT);

$prep_search_query->execute();

$array_search = $prep_search_query->fetchAll(PDO::FETCH_ASSOC);

print_r($array_search);

// The output is empty

花了一两个小时,寻找可能的错误后,我终于决定来这里,因为我不知道为什么会这样......

我正在编写搜索页面,它必须使用PDO。上面的代码不起作用,但是,下面的代码确实如此:

//$sch = '%test%';

$select_search_query = "(
        SELECT 
            GROUP_CONCAT(name, ' ', surname) AS result
          FROM users
        WHERE 
        (
            email LIKE '%test%' OR 
            name LIKE '%test%' OR 
            surname LIKE '%test%'
        ) 
        AND 
            id_p = 1
    )";

$prep_search_query = $connection->prepare($select_search_query);

$prep_search_query->execute();

$array_search = $prep_search_query->fetchAll(PDO::FETCH_ASSOC);

print_r($array_search);

// The output is a very long array

似乎问题位于LIKE中,但我找不到解决方案,我测试了很多东西并且没有得到任何结果。谢谢!

1 个答案:

答案 0 :(得分:4)

不幸的是,当您执行PDO bindParam时,您无法重复使用相同的占位符:

email LIKE :sch OR 
name LIKE :sch OR 
surname LIKE :sch

应该是这样的:

email LIKE :sch1 OR 
name LIKE :sch2 OR 
surname LIKE :sch3

然后在下面:

$prep_search_query->bindValue(":sch1", $sch); //or bindParam I guess will work as well
$prep_search_query->bindValue(":sch2", $sch);
$prep_search_query->bindValue(":sch3", $sch);