What is a simple solution for mysqli bind_param dynamic arguments in PHP?

To dynamically build bind_param, I found this on other SO posts.

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

Can someone break this in English? I especially lost that the first argument is an array.

+6
mysqli
source share
3 answers
 array($stmt, 'bindparams') 

is a PHP way to identify the bind_params method for the $stmt object, since PHP 5 you no longer need to use & in front (and mysqli is PHP 5, so it looks like a crash in the older record).

you can see a similar example here

So

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

basically means

 $stmt->bind_params($array_of_params[0], $array_of_params[1] ... $array_of_params[N]) 
+15
source share

As far as I know, you cannot pass the result, for example. $userid == "ALL" to the mysqli-statement-Object bind_param method because this method wants the parameters to be passed by reference. Obviously, this is not possible as a result of an expression evaluated "in place".

As a workaround, I changed the second part of the program to

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

Thus, the result of a boolean operation can be passed by reference.

+2
source share

There is a very easy way to do this.

create this prepared statement:

 select * from mytable where status = ? and (userid = ? or ?) and (location = ? or ?) order by `date` desc, time desc limt ? 

and pass args to bind as follows:

 $stmt = $mysqli->prepare( [statement above] ); $stmt->bind_param( "siiiii", "active", $userid, $userid == "ALL", $location, $location == "ALL", $limit); 

The predicate (user_id = ? or ?) Will be true if user_id is equal to the first replaced parameter or when the second replaced parameter is true.

$user_id when converted to int will be its value when it is a string representation of a number, or zero otherwise. The expression $userid == "ALL" will be evaluated before the boolean, which will be passed to bind_param . We cannot tell bind_param that the parameter is logical (the format string understands only the string, int, double and blob), so bind_param converts the boolean value into int, which works for us.

As long as there is no user_id or location_id in the database, you are fine.

+1
source share

All Articles