7

要动态构建 bind_param,我在其他 SO 帖子中发现了这一点。

call_user_func_array(array(&$stmt, 'bindparams'), $array_of_params);

有人可以用简单的英语为我分解吗?我特别迷失了第一个参数是一个数组。

4

3 回答 3

16
array($stmt, 'bindparams') 

是 PHP 在 object 上识别方法 bind_params 的方式$stmt,因为 PHP 5 您不再需要使用&前面的方法(而 mysqli 是 PHP 5,所以这看起来像是旧帖子中的一个小故障)。

你可以在这里看到一个类似的例子

所以

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])
于 2009-04-16T07:39:34.470 回答
2

据我所知,您不能将 eg 的结果传递 $userid == "ALL" 给 mysqli-statement-Object 的 bind_param 方法,因为该方法希望通过引用传递参数。显然,对于“就地”评估的表达式的结果,这是不可能的。

作为一种解决方法,我将程序的第二部分更改为

$userIdEmpty = $userid == "ALL";
$locationEmpty = $location = "ALL";
$stmt->bind_param( "siiiii", 
  "active", $userid, $userIdEmpty,
  $location, $locationEmpty,
  $limit);

像这样,布尔运算的结果可以通过引用传递。

于 2011-10-19T06:42:39.393 回答
1

有一种更简单的方法可以做到这一点。

创建这个准备好的语句:

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一个参数是布尔值(格式字符串只能理解 string、int、double 和 blob),因此 bind_param 会将布尔值转换为 int,这对我们有用。

只要数据库中没有 user_id 或 location_id 为零,就可以了。

于 2009-04-16T07:52:42.643 回答