PDO执行多个OR

时间:2013-08-19 20:33:50

标签: php pdo

以下是我用来动态加载新闻文章到网页的代码。 $ dbConn->传递单个时正确执行
WHERE (SELECT * FROM newsitem WHERE subcategoryID=12 ORDER BY posted DESC)
但是在传递时未能返回结果

(SELECT * FROM newsitem WHERE subcategoryID=1 || subcategoryID=12 || subcategoryID=27 || subcategoryID=27 || subcategoryID=28 || subcategoryID=29 || subcategoryID=30 || subcategoryID=31 || subcategoryID=32 || subcategoryID=43 ORDER BY posted DESC)

这是生成上述查询的代码:

`$ strHTML =“”;         $ strHTML。=“”;

    if(strpos($params['subcatid'], "|") < 0){
        $q = "SELECT * FROM newsitem WHERE subcategoryID=".$params['subcatid']." ORDER BY posted DESC";
    } else {
        $q = "SELECT * FROM newsitem WHERE ";
        $idArr = explode("|", $params['subcatid']);

        for($i = 0; $i < count($idArr); $i++){
            $q .= "subcategoryID=".$idArr[$i]." || ";
        }
        $q = substr($q, 0, -4)." ORDER BY posted DESC";
    }
    return $q;

    $pstmt = $dbConn->prepare($q);
    $pstmt->execute();

    for($i = 0; $i < $params['numarts']; $i++){
        $row = $pstmt->fetch(PDO::FETCH_ASSOC);
        if($i == 0){
            $startArt = $row['newsitemID'];
        }
        $strHTML .= "<a href='javascript:cNews.get(".$row['newsitemID'].")'>".$row['headline']."</a><br />";
    }
    $numPages = ceil($pstmt->rowCount() / 10);
    $strHTML .= "<div id='articleNav' style='font-weight: bold; padding-top: 5px; width: 50%;'>Page: 1 of ".$numPages."<img src='/files/images/sitewide/next.gif' style='float: right;''></div>";
    $strHTML .= "<div id='startArticleID' style='visibility: hidden;'>".$startArt."</div></div><div id='newsarticle' style='padding-top: 20px;'>&nbsp;</div>";
    //return $params['id']." ".$params['subcatid'];
    return $strHTML;`

运行此函数时$params['subcatid']传递subcatid='12'或管道分隔列表subcatid='1|12|26|27|28|29|30|31|32|44'。生成查询,然后准备,执行。如前所述,当只有一个subcategoryID时,结果会按预期返回;传递多个OR subcategoryID时,不会返回任何结果。

我通过直接将查询复制并粘贴到数据库来测试这一点,并且都按预期返回结果。

传递复杂查询时会发生什么?

2 个答案:

答案 0 :(得分:0)

正如你在评论中被告知的那样,多个OR可以用非常方便的IN运算符代替。

然而,使用准备好的陈述来制作它并不容易。你走了:

必须创建一个包含表示每个数组成员的占位符的查询,然后绑定此数组值以供执行:

$ids = explode("|", $params['subcatid']);
$in  = str_repeat('?,', count($arr) - 1) . '?';
$sql = "SELECT * FROM table WHERE column IN ($in)";
$stm = $db->prepare($sql);
$stm->execute($ids);
$data = $stm->fetchAll();

答案 1 :(得分:-1)

请勿使用SQL OR执行此操作,而是使用IN执行此操作

假设id是一个整数的例子:

$q = "SELECT * FROM newsitem WHERE ";

$idArr = explode("|", $params['subcatid']);
$placeholders = array_fill(0,count($idArr),'?');
$placeholders_str = implode(',',$placeholders);

$q .= "subCategoryId IN ($placeholders_str)";    

$q .= " ORDER BY posted DESC";

免责声明:我在这里没有做任何验证,只是展示了逻辑。