I'm converting my SQL to prepared statements, but I'm stuck on something. My SQL query is built step by step, so the number of variables are unknown. If I want this:
$stmt->bind_param('sssii', $variable1, $variable2, $variable3, $startpoint, $limit);
And I have these two variables:
$var1 = "sss"; <Br />
$var2 = "$variable1, $variable2, $variable3";
How do I incorporate them in the above string? I tried this, but without the correct result..
$stmt->bind_param('{$var1}ii', ".$var2.", $startpoint, $limit);
Var 2 is the problem... Thanks!
You can do it for types like this: $stmt->bind_param($var1.'ii', ...)
but not for arguments as it's have to be passed by reference. But there is workaround. You can find it in documentation comments: mysqli-stmt.bind-param
It uses reference class for it:
$ref = new ReflectionClass('mysqli_stmt');
$method = $ref->getMethod("bind_param");
$method->invokeArgs($stmt, $args);
$res->execute();
Where $args
is array with all your types and paramteres. For your example:
$args[] = 'sssii';
$args[] = $variable1;
$args[] = $variable2;
(...)
$args[] = $startpoint;
$args[] = $limit;
If you have data like this value1, value2, value3
you can try to explode
it and array_merge
with $args
.
$foo1 = 'bar1';
$foo2 = 'bar2';
$foo3 = 'bar3';
$foo4 = 'bar4';
$limit = 10;
$stmt->prepare('SELECT * FROM example_table WHERE col1=? AND col2=? AND col3=? AND col4=? LIMIT ?');
$args[] = 'ssssi';
$args[] = $foo1;
$args[] = $foo2;
$args[] = $foo3;
$args[] = $foo4;
$ref = new ReflectionClass('mysqli_stmt');
$method = $ref->getMethod('bind_param');
$method->invokeArgs($stmt, $args);
$res->execute();
Query will look like this:
SELECT * FROM example_table WHERE col1="bar1" AND col2="bar2" AND col3="bar3" AND col4="bar4"
您必须使用双引号来获取变量插值。
$stmt->bind_param("{$var1}ii", ".$var2.", $startpoint, $limit);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.