bind_param 中的参数数量未知 [英] unknown number of parameters in bind_param
问题描述
当您不知道将要接收的参数数量时,你们会怎么做?
What do you guys do when you don't know the number of parameters that you are going to receive?
例如:
if($a==1) $filter.=" AND u.name = ?";
if($b==1) $filter.=" AND u.address = ?";
if($c==1) $filter.=" AND u.age = ?";
if($d==1) $filter.=" AND u.city = ?";
ETC...
$stmt->prepare("SELECT id
FROM users u
WHERE u.cp = ?
".$filter);
$stmt->bind_param("i", $cp);
现在呢?如果您收到 $a = 1
,您将收到错误消息,因为您只在 bind_param
上传递了 1 个参数.所以你不知道你是否会收到 1、2、3 或 4 个参数,我不想制作很多 IF
或者我必须使用循环来计算参数?
And now? if you are receiving $a = 1
you will get an error because you are only passing 1 parameter on the bind_param
. So you don't know if you are going to receive 1, 2, 3 or 4 params and I don't want to make a lot of IF
or I must use a loop to count the number of parameters?
推荐答案
您必须在添加条件时管理参数列表(类型和值).这意味着您需要使用 call_user_func_array
将值列表传递给 bind_param
.
You'll have to manage the list of arguments (type and value) as you add the conditions. This means you need to use call_user_func_array
to pass the list of values to bind_param
.
基本上,在您的每个 if
语句中,不仅要添加条件,还要添加参数类型(例如 $types .= 'i'
)和参数(例如 $args[]=$arg
).
Basically, in each of your if
statements, not only add the condition, but also add the parameter type (e.g. $types .= 'i'
) and the parameter (e.g. $args[]=$arg
).
您会在 bind_param
文档的此注释中找到一个关于如何执行此操作的好示例:http://www.php.net/manual/en/mysqli-stmt.bind-param.php#109256
You'll find a good example on how to do this in this comment of the bind_param
documentation: http://www.php.net/manual/en/mysqli-stmt.bind-param.php#109256
这篇关于bind_param 中的参数数量未知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!