Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

php - How can I use for loop in a IN statement in this situation?

I am using for loop for select in. The issue I am encounter is I have multiple value in the IN statement. I know IN(term_1, term_2) we need a period to separate each one. When I use for loop, I don't know how to append the period. First, it was inside the statement parenthesis instead of at the end.

<?php
for ($i = 0; $i <= 8; $i++) {
    $stm =$db->prepare("SELECT id FROM sign WHERE term IN (:term_$i) GROUP BY os.user_id order by COUNT(os.user_id) DESC ");

        $stm->bindParam(":term_$i", $search_text[$i]);

        $stm->execute();
    }

?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Prepared statement placeholders can only represent SINGLE values.

e.g.

$foo = '1,2,3';
$db->prepare("SELECT ... WHERE foo in (:foo)");
bind(':foo', $foo);

would create a query that's interpreted as

SELECT ... WHERE foo IN ('1,2,3');

Note the quotes - your three separate numbers are now a single-valued string, and the query runs as if it had been written:

SELECT ... WHERE foo='1,2,3'

You'd have to build a dynamic statement and create as many placeholders as you have values.

foreach ($values as $val) {
     $placeholders[] = '?';
}
$sql = "SELECT ... WHERE foo IN (" . implode(',', $placeholders) . ")";
...prepare/bind other values
$stmt->execute($values);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...