0

下面是我用来将新闻文章动态加载到网页的代码。$dbConn->execute 在传递单个时正确触发,
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

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

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

4

2 回答 2

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();
于 2013-08-19T20:49:45.530 回答
-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";

免责声明:我在这里不做任何验证,只是演示逻辑。

于 2013-08-19T20:46:52.687 回答