PDO准备语句Like和OR语句一起使用

时间:2012-01-27 00:24:16

标签: php pdo

我试图说明是否所有'或'匹配然后显示。如果它远离保管人那么显示(LIKE) 对狮子座,是的,我试过:监护人继续整个代码。我评论了你的建议,因为这是现在有用的。 (也改了sql)。我很好奇第一个问题,我试图让'计数'很重要。让我知道。感谢。

$q = $_GET['q'];
$STH = $dbh->prepare("SELECT COUNT(*) FROM inv_assets WHERE po = :query OR serialNum = :query OR dop = :query OR purchaseFrom = :query OR custodian = :query");
    $STH->bindParam(':query', $q);
            //$STH->bindParam(':custodian', '%'.$q.'%');
    $STH->execute();

    if ($STH->fetchColumn() > 0) {
        $STH = NULL;
        $STH = $dbh->prepare("SELECT * FROM inv_assets WHERE po = :query OR serialNum = :query OR dop =:query OR purchaseFrom = :query OR custodian = :query");
        $STH->bindParam(':query', $q);
        //$STH->bindParam(':custodian', '%'.$q.'%');
                    $STH->execute();
        showTable($STH,$perms);

3 个答案:

答案 0 :(得分:2)

LIKE取代=而不是OR

示例:

SELECT first_name, last_name 
FROM student_details 
WHERE first_name LIKE 'S%' OR last_name LIKE 'A%';

看看这里:SQL Comparison Keywords

答案 1 :(得分:2)

如何进行PDO LIKE查询的示例。

$STH = $dbh->prepare("SELECT COUNT(*) FROM inv_assets 
                      WHERE po = :query OR serialNum = :query OR dop = :query 
                      OR purchaseFrom = :query OR custodian LIKE :custodian");

$ret = $STH->execute(array(':custodian' => '%'.$query.'%',':query' => $query));

bindParam示例:

<?php

$STH = $dbh->prepare("SELECT COUNT(*) FROM inv_assets 
                      WHERE po = :query OR serialNum = :query OR dop = :query 
                      OR purchaseFrom = :query OR custodian LIKE :custodian");

$STH->bindParam(':custodian', '%'.$q.'%');
$STH->bindParam(':query', $q);
$STH->execute();

?>

答案 2 :(得分:0)

<?php

$STH = $dbh->prepare("SELECT COUNT(*) FROM inv_assets 
                      WHERE po = :query OR serialNum = :query OR dop = :query 
                      OR purchaseFrom = :query OR custodian LIKE :custodian");

$custodian = "%".$q."%";
$STH->bindParam(':custodian', $custodian);
$STH->bindParam(':query', $q);
$STH->execute();

?>

这将避免通过参考错误传递参数2并且工作