PHP PDO 仅使用 bindValue & 插入数组的最后一个值绑定参数 [英] PHP PDO only last value of array gets inserted using bindValue & bindParam

查看:39
本文介绍了PHP PDO 仅使用 bindValue & 插入数组的最后一个值绑定参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当下面的代码被执行时,只有数组 charlie 的最后一个值被插入到表中.

When below code is executed, only the last value of the array charlie gets inserted in the table.

$this->array = $array; //Array ( [0] => alpha [1] => bravo [2] => charlie )

$query = "INSERT INTO test SET Name = :Name";
$sql = $this->conn->prepare($query);

foreach($this->array as $k => &$v) {
    $sql->bindValue(":Name" , $v , PDO::PARAM_STR);
}
$sql->execute();

我也使用 bindParam 得到相同的结果.

Im getting the same result using bindParam as well.

谁能帮我指出我遗漏了什么.

Can someone help me point out what I'm missing.

我完全不知所措.

推荐答案

这仅使用最后一个值执行插入,因为它是绑定到语句的最后一个值.在循环的每次迭代中调用 execute.

This is only executing the insert with the last value as it's the last value that is bound to the statement. Call execute in each iteration of the loop.

foreach($this->array as $k => &$v) {
    $sql->bindValue(":Name" , $v , PDO::PARAM_STR);
    $sql->execute();
}

这篇关于PHP PDO 仅使用 bindValue & 插入数组的最后一个值绑定参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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