下面是我用来将新闻文章动态加载到网页的代码。$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;'> </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
。
我通过将查询直接复制并粘贴到数据库来测试这一点,并且两者都按预期返回结果。
传递复杂查询时会发生什么?