mysqli使用IN运算符和另一个占位符准备了语句 [英] mysqli prepared statements with IN operator and one more placeholder

查看:64
本文介绍了mysqli使用IN运算符和另一个占位符准备了语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码有些混乱,请查看我的代码并建议我如何使用In运算符在查询中传递另一个参数.

I have some confusion in my code please view my code and suggest me how to pass another parameter in query using with In operator.

$cat=1;
$lastnames = $ids;
$arParams = array();

foreach($lastnames as $key => $value) 
        $arParams[] = &$lastnames[$key];
        ;

$count_params = count($arParams);
$int = str_repeat('i',$count_params); 
array_unshift($arParams,$int); 
$q = array_fill(0,$count_params,'?'); 
$params = implode(',',$q);

$qry1=$dblink->prepare("SELECT * FROM course_details WHERE category=$cat and cat_id IN ($params)");
call_user_func_array(array($qry1, 'bind_param'), $arParams);
$qry1->execute();
$qry1_res=$qry1->get_result();

while($rowset1=$qry1_res->fetch_array()){
    print_r($rowset1);
}

我无法像我之前那样绑定我的猫ID.请帮助我,谢谢你

I can't bind my cat id as like preapred. please help me Thank you

推荐答案

您的常识答案略有变化,但我没有意识到您可以做到(尽管在某种意义上是可以做到的)...

A slight variation on Your Common Sense's answer, and something I didn't realise you could do (although it makes sense in a way)...

$cat=1;
$lastNames = $ids;

$count_params = count($lastNames);
$int = str_repeat('i',$count_params+1);
$q = array_fill(0,$count_params,'?');
$params = implode(',',$q);
$qry1=$dblink->prepare("SELECT * FROM course_details WHERE category=? and cat_id IN ( $params )");

$qry1->bind_param( $int, $cat, ...$lastNames);
$qry1->execute();
$qry1_res=$qry1->get_result();
while($rowset1=$qry1_res->fetch_array()){
        print_r($rowset1);
}

唯一真正的不同是对bind_param的调用,而不是将项目合并到数组中,只需在使用PHP 5.6+的数组填充(...)之前将其作为另一个参数列出即可.

The only real different is the call to bind_param, rather than merging the item into the array, just list it as another parameter before using the array fill (...) from PHP 5.6+.

更新: 从注释中可以看出,PHP版本不支持splat:(...,因此请返回原始版本...

Update: From the comment, the version of PHP doesn't support splat :(... so going back to original...

$cat=1;
$lastnames = $ids;
$arParams = array();

array_unshift($lastnames,$cat);
foreach($lastnames as $key => $value)   {
    $arParams[] = &$lastnames[$key];
}

$count_params = count($arParams);
$int = str_repeat('i',$count_params);
array_unshift($arParams,$int);
$q = array_fill(0,$count_params-1,'?');
$params = implode(',',$q);

$qry1=$dblink->prepare("SELECT * FROM course_details WHERE category=? and cat_id IN ( $params )");
call_user_func_array(array($qry1, 'bind_param'), $arParams);
$qry1->execute();
$qry1_res=$qry1->get_result();

while($rowset1=$qry1_res->fetch_array()){
    print_r($rowset1);
}

这会将类别添加到项目列表中,但请注意array_fill()使用count-1作为??因为猫已经在那里了.

This adds the category into the list of items, but note the array_fill() uses count-1 as the ? for the cat is already there.

这篇关于mysqli使用IN运算符和另一个占位符准备了语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆