【发布时间】:2009-04-16 06:59:32
【问题描述】:
要动态构建 bind_param,我在其他 SO 帖子中找到了这个。
call_user_func_array(array(&$stmt, 'bindparams'), $array_of_params);
谁能帮我用简单的英语解释一下?我特别迷失了第一个参数是一个数组。
【问题讨论】:
要动态构建 bind_param,我在其他 SO 帖子中找到了这个。
call_user_func_array(array(&$stmt, 'bindparams'), $array_of_params);
谁能帮我用简单的英语解释一下?我特别迷失了第一个参数是一个数组。
【问题讨论】:
array($stmt, 'bindparams')
是 PHP 识别对象 $stmt 上的方法 bind_params 的方式,因为 PHP 5 您不再需要在前面使用 &(而 mysqli 是 PHP 5,所以这看起来像旧版本中的故障发布)。
你可以看到类似的例子here
所以
call_user_func_array(array($stmt, 'bindparams'), $array_of_params);
基本意思
$stmt->bind_params($array_of_params[0], $array_of_params[1] ... $array_of_params[N])
【讨论】:
据我所知,您无法传递例如的结果。
$userid == "ALL"
到 mysqli-statement-Object 的 bind_param 方法,因为该方法希望通过引用传递参数。显然,这对于“就地”评估的表达式的结果是不可能的。
作为一种解决方法,我将程序的第二部分更改为
$userIdEmpty = $userid == "ALL";
$locationEmpty = $location = "ALL";
$stmt->bind_param( "siiiii",
"active", $userid, $userIdEmpty,
$location, $locationEmpty,
$limit);
这样,布尔运算的结果可以通过引用传递。
【讨论】:
有一种更简单的方法可以做到这一点。
创建这个准备好的语句:
select * from mytable
where status = ? and (userid = ? or ?)
and (location = ? or ?)
order by `date` desc, time desc
limt ?
并像这样传递参数来绑定:
$stmt = $mysqli->prepare( [statement above] );
$stmt->bind_param( "siiiii",
"active", $userid, $userid == "ALL",
$location, $location == "ALL",
$limit);
当 user_id 等于第一个替换参数或第二个替换参数为 true 时,谓词 (user_id = ? or ?) 将为 true。
$user_id 转换为 int 时将是它的值,如果它是数字的字符串表示形式,否则为零。表达式$userid == "ALL" 将计算为一个布尔值,该布尔值将传递给bind_param。我们无法告诉bind_param 参数是布尔值(格式字符串只能理解字符串、int、double 和 blob),因此 bind_param 会将布尔值转换为 int,这对我们有用。
只要数据库中没有 user_id 或 location_id 为零,就可以了。
【讨论】: