如何使用pdo准备的语句中的条款



我以这种格式在mySQL内部的字段中存储了一些数据: 1,5,9,4
我命名了此字段相关。现在,我想在子句中使用 pdo 中的中的此字段。我将该字段内容存储在$related variabe中。这是我的下一个代码:

$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)。我做错了什么?

使用命名的位置支架

$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)), ', ').')';

您需要与" in" in in value的任务多数?占位符。

so:

$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 AS-IS。

相关内容

  • 没有找到相关文章

最新更新