说我有这个:
$term_query = "AND t.slug IN ('" . $term_slugs . "') ";
其中$term_slugs
id是这样的数组:
array('foto', 'video');
如果我做一个简单的内爆(),它将无法工作,因为它不能是“照片,视频”。所以我应该做一个foreach循环来构建“'照片','视频'”。 但我不能认为这是唯一的方法......真的很不优雅。还有其他更聪明的方法吗?
答案 0 :(得分:4)
您可以使用:
$term_query = "AND t.slug IN ('" . implode("','",$term_slugs) . "') ";
但准备好的陈述更好:
$term_query = "AND t.slug IN ('" . implode(",",array_fill(0,count($term_slugs),"?") . ") "
现在您可以绑定参数:
PDO绑定
$stmt = $pdoObject->prepare($query); //Query is the full query which contains the parametrised $term_query
foreach ($term_slugs as $index => &$slug) {
$stmt->bindParam($index+1,$slug); //+1 because PDO parameters are index starting from 1
}
MySQLi绑定
$stmt = mysqli_prepare($query); //Query is the full query which contains the parametrised $term_query
$refArray = [ $stmt, array_fill(0,$term_slugs),"s") ]; //first two parameters for bind param
foreach ($term_slugs as $index => &$slug) {
$refArray[] = &$slug; //mysqli_bind_param needs references
}
call_user_func_array('mysqli_bind_param',$refArray);