问题
Is there a way to use MySQLi prepared statements without passing references?
[Background: I'm extremely new to PHP and to MySQL but I inherited a private WordPress plugin to maintain and so I'm learning both as I go.]
I understand that prepared statements are useful for preventing SQL injections and potentially also for speeding up queries (if the statements are kept around) but the need for referenced variables seems odd. Is the idea that one calls bind_param up front and then when making subsequent queries just sets data into those bound variables rather than interacting with the statement at all?
Right now the code I'm refactoring has 17 variables that it passes into bind_param
. I made a class to contain all of the data so I don't need to pass 17 variables from function to function anymore but the below obviously fails because my class isn't returning references:
$stmt->bind_param('ssssssisssssssssi',
$my_class->get(FIELD_ONE),
$my_class->get(FIELD_TWO),
/*...x15 more...*/)
Given that the code is currently discarding $stmt
immediately after $stmt->execute()
(so there aren't long-term variables to track), is there any way for me to use prepared statements without bothering to create temporary variables just so I can bind them? Is there an alternative class/interface I could or should be using?
Thanks!
回答1:
Yes, there is.
Some time ago an invaluable feature has been added to PHP - an argument unpacking operator. It has a billion uses, and helping you in this situation is among them.
Just add ...[
before your list of values and ]
after - and voila, it works!
$stmt->bind_param('ssssssisssssssssi', ...[
$my_class->get(FIELD_ONE),
$my_class->get(FIELD_TWO),
/*...x15 more...*/
]);
A hint: this useful operator could be also used to encapsulate that boring prepare/bind/execute process in a simple function.
回答2:
Is the idea that one calls bind_param up front and then when making subsequent queries just sets data into those bound variables rather than interacting with the statement at all?
Yes. Typical operation of a prepared statement with bound variables would be:
prepare statement;
bind params;
for (some loop) {
assign values to params;
execute statement;
}
In MySQLi you only have the option of bind_param so are restricted to passing references. If you don't mind changing interfaces, you could switch to PDO which has a bindValue function which will work with values rather than references. PDO
will also let you avoid a call to bind parameters/values altogether by simply passing an array of values to the statement execute call.
来源:https://stackoverflow.com/questions/55486423/use-php-mysqli-prepared-statements-without-references