对数组和循环使用 bind_param [英] Using bind_param with arrays and loops

查看:18
本文介绍了对数组和循环使用 bind_param的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据这个示例 对于准备好的语句,我首先绑定参数,然后为参数设置值.

according to this example for prepared statements I first bind parameters and then set values for the parameters.

假设我有一个二维数组 $alias

Let's assume I have a 2-dim array $alias

$array1 = [
    'id' => 1,
    'tstamp' => 123456789,
    'alias' => '$alias',
];

$array2 = [
    'id' => 1,
    'tstamp' => 123456789,
    'alias' => '$alias2',

];

$alias = [$array1, $array2];

为什么这段代码有效

$insert = 'INSERT INTO abcdef VALUES (?,?,?)';
$insertStmt = $conn->prepare($insert);
foreach ($alias as $array) {
    $insertStmt->bind_param('iis', $array['id'], $array['tstamp'], $array['alias']);
    $insertStmt->execute();
}

这不是吗?

$insert = 'INSERT INTO abcdef VALUES (?,?,?)';
$insertStmt = $conn->prepare($insert);
$insertStmt->bind_param('iis', $array['id'], $array['tstamp'], $array['alias']);
foreach ($alias as $array) {
   $insertStmt->execute();
}

如果我必须一直绑定参数,那么流量会增加很多,不是吗?

If I have to bind the parameters all the time there's a lot more trafic, isn't it?

推荐答案

bind_param() 通过引用特定的zval 容器.在循环的每次迭代中,都会为新的数组符号表分配自己的 zval 容器.如果在绑定时 zval 容器不存在,它们将被创建.这可以用以下代码显示:

bind_param() binds by reference to a specific zval container. On each iteration of the loop a new array symbol table is allocated with its own zval containers. If at the time of binding the zval containers do not exist they will be created. This can be shown with the following code:

$insertStmt = $conn->prepare('INSERT INTO abcdef VALUES (?,?,?)');
$insertStmt->bind_param('sss', $array['id'], $array['tstamp'], $array['alias']);
var_dump($array);

输出:

array (size=3)
  'id' => null
  'tstamp' => null
  'alias' => null

即使我们没有在任何地方声明 $array,绑定还是用空值隐式地创建了它.绑定将继续指向这个空数组.

Even though we didn't declare the $array anywhere, the binding implicitly created it with null values. Bindings will keep on pointing to this empty array.

当然,当我们开始迭代别名数组时,每次都会重新创建$array.我们绑定参数的旧数组符号表现在不见了.我们还没有将任何东西绑定到新数组.

Of course when we start iterating the alias array, the $array will be created anew each time. The old array symbol table, to which we bound the parameters is now gone. We haven't bound anything to the new array.

要解决这个问题,您可以简单地将 bind_param() 移动到 foreach 循环内:

To solve this you can simply move the bind_param() inside the foreach loop as:

$insertStmt = $conn->prepare('INSERT INTO abcdef VALUES (?,?,?)');
foreach ($alias as $array) {
    // bind to the new zval containers every iteration
    $insertStmt->bind_param('sss', $array['id'], $array['tstamp'], $array['alias']);
    $insertStmt->execute();
}

这篇关于对数组和循环使用 bind_param的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆