如何使用带有IN子句的PDO预处理语句?

时间:2016-06-15 06:08:37

标签: php mysql pdo prepared-statement in-clause

我以一种格式将一些数据存储在MySQL内的字段中: 1,5,9,4
我将此字段命名为 related 。现在我想在 IN子句中使用 PDO 中的此字段。我将该字段内容存储在$related变量中。这是我的下一个代码:

$sql = "SELECT id,title,pic1 FROM tbl_products WHERE id IN (?) LIMIT 4";
$q = $db->prepare($sql);
$q->execute(array($related));
echo $q->rowCount();

但执行此代码后,我只能获取一条记录,而我必须获取4条记录(1,5,9,4)。我做错了什么?

2 个答案:

答案 0 :(得分:0)

您需要与“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

答案 1 :(得分:-1)

使用命名的占位符

$values = array(":val1"=>"value1", ":val2"=>"value2", ":val2"=>"$value3");
$statement = 'SELECT * FROM table WHERE `column` in(:'.implode(', :',array_keys($values)).')';

使用??

$values = array("value1", "value2", "$value3");
$statement = 'SELECT * FROM table WHERE `column` in('.trim(str_repeat(', ?', count($values)), ', ').')';