php - 多次调用 $stmt->bind_param

标签 php mysqli prepared-statement bindparam

我处于一种情况,我想构建一个代码,以这种格式获取 $bindParam 变量:

$bindParams = [$type1 => $param1, $type2 => $param2, ... ]

我想构建一些代码,将这些参数动态添加到准备好的语句中。
这是我到目前为止构建的代码:

$mysql = new mysqli("localhost", "root", "", "db1");
$stmt = $mysql->prepare($sql);
foreach($bindParams as $type => $data) {
    $stmt->bind_param($type, $data);
}
$stmt->execute();
$result = $stmt->get_result();
// and after perhaps twiddling with the result set, but this is not the case .....

对于你的例子

$sql = "INSERT INTO table1 (name, age) VALUES (?,?);"

$bindParams = ["s" => "hello", "i" => 15] 

这并不总是具有这种结构,它可以更改为例如 $bindParams = ["s"=> "hello", "i"=> 15, "d"=> 22.5] $sql 分别发生变化。

在编译器第一次转到 $stmt->bind_param($type, $data); 后,firefox 会清除此错误:

Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in D:\PHP\tr.php on line 23

我知道 PDO 支持,如前所述 here at the end of the page.但也许正如您所料,我不是 PDO 的粉丝,所以 ;)
我的另一个选择是使用 php 中可用的 eval() 解决方法,但这超出了我的想象。

还有其他方法吗?

最佳答案

我遇到了同样的问题,并找到了更简单的答案:

$array_of_values = array( "Brasil", "Argentina" );
$types = "ss";
$mysqli_stmt->bind_param( $types, ...$array_of_values );

这称为“参数解包”,从 PHP 5.6 开始可用

关于php - 多次调用 $stmt->bind_param,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38857768/

相关文章:

php - 如果输入有一个或多个问号,则从数据库获取数据。

php - Slim 3 控制台执行 cron

php - 在 php 中使用 "ORDER BY"查询未提供准确的结果

php - 在mysql中如何使用增量i=1,i++?

php - 为什么 mysqli 绑定(bind)函数不能正确处理我的字符串?

mysql - 我可以在 JDBC 准备好的语句中替换除参数之外的其他内容吗?

php - 这个可以用SQL注入(inject)吗?

php - mysql查询使用另一个查询的数组结果

php - 根据从父表获得的两个案例连接两个表

java - 在 JDBC 中,为什么准备好的语句的参数索引从 1 而不是 0 开始?