mysql语句带变量参数_MySQL准备的带有可变大小变量列表的语句

I had a similiar problem today and I found this topic. Looking at the answers and searching around the google I found a pretty solution.

Although, my problem is a little bit more complicated. Because I have fixed binding values and dynamic too.

This is the solution.

$params = array()

$all_ids = $this->get_all_ids();

for($i = 0; $i <= sizeof($all_ids) - 1; $i++){

array_push($params, $all_ids[$i]['id']);

}

$clause = implode(',', array_fill(0, count($params), '?')); // output ?, ?, ?

$total_i = implode('', array_fill(0, count($params), 'i')); // output iiii

$types = "ss" . $total_i; // will reproduce : ssiiii ..etc

// %% it's necessary because of sprintf function

$query = $db->prepare(sprintf("SELECT *

FROM clients

WHERE name LIKE CONCAT('%%', ?, '%%')

AND IFNULL(description, '') LIKE CONCAT('%%', ?, '%%')

AND id IN (%s)", $clause));

$thearray = array($name, $description);

$merge = array_merge($thearray, $params); // output: "John", "Cool guy!", 1, 2, 3, 4

// We need to pass variables instead of values by reference

// So we need a function to that

call_user_func_array('mysqli_stmt_bind_param', array_merge (array($query, $types), $this->makeValuesReferenced($merge)));

And the function makeValuesreferenced:

public function makeValuesReferenced($arr){

$refs = array();

foreach($arr as $key => $value)

$refs[$key] = &$arr[$key];

return $refs;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值