我处于一种情况,我想构建一个代码,以这种格式获取 $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/