您需要儘可能多的?
佔位符作爲您的「IN」值。
所以:
$related = array(1,2,3); // your "IN" values
$sql = "SELECT id,title,pic1 FROM tbl_products WHERE id IN (";
$questionmarks = "";
for($i=0;$i<count($related);$i++)
{
$questionmarks .= "?,";
}
$sql .= trim($questionmarks,",");
$sql .= ") LIMIT 3;";
// echo $sql; // outputs: SELECT id,title,pic1 FROM tbl_products WHERE id IN (?,?,?) LIMIT 3;
$q = $db->prepare($sql);
$q->execute($related); // edited this line no need to array($related), since $related is already an array
echo $q->rowCount();
https://3v4l.org/No4h1
(如果你還想要4個返回記錄擺脫LIMIT 3
)
更優雅,你可以使用str_repeat追加你的佔位符這樣的:
$related = array(1,2,3); // your "IN" values
$sql = "SELECT id,title,pic1 FROM tbl_products WHERE id IN (";
$sql .= trim(str_repeat("?,",count($related)),",");
$sql .= ") LIMIT 3;";
// echo $sql; // outputs: SELECT id,title,pic1 FROM tbl_products WHERE id IN (?,?,?) LIMIT 3;
$q = $db->prepare($sql);
$q->execute($related); // edited this line no need to array($related), since $related is already an array
echo $q->rowCount();
https://3v4l.org/qot2k
而且,通過再次閱讀你的問題,我可以猜您$related
變量只是一個string
與像1,40,6,99
值逗號分隔的數字。如果是這種情況,您需要將其設爲array
。做:$related = explode($related,",");
使它成爲一個數組數組。然後在您的execute
方法中按原樣傳遞$related
。
可能重複[FIND \ _IN \ _SET()vs IN()](http://stackoverflow.com/questions/4155873/find-in-set-vs-in) –
常見的路徑是使用關係的額外表格。這是不好的數據庫設計。 –
@GeraldSchneider我知道,這只是我的問題的一個示例。 –