我正在PDO中学习和学习新知识。在PDO中使用数组会给我带来困难。我正在使用PDO语法开发简单的Web应用程序。一切都很顺利,但我无法从单个提交按钮更新多个值。
HTML表格
<td>
<input type="number" name="roll[]" value="<?php echo $roll?>">
</td>
<td>
<input type="text" name="name[]" value="<?php echo $name?>">
<td>
我可以打印数据。
if(isset($_POST['submit'])){
$name = $_POST['name'];
$roll = $_POST['roll'];
foreach( $roll as $key => $n ){
print "The name is ".$name[$key]." and email is ".$roll[$key].", thank you\n";
}
}
但我无法一次更新多个值。也许是因为在PDO中组合数组方面缺乏知识。我在互联网上搜索过。但我发现只有先进的问题和答案。我在这个问题上找不到任何示例或讨论主题。 我确信我100%错了,所以下面的代码不起作用。请帮助如何使用数组
进行更新PHP代码
if(isset($_POST['submit'])){
$name = $_POST['name'];
$roll = $_POST['roll'];
foreach( $roll as $key => $n ){
$sql = "UPDATE student SET name=:name WHERE roll=:roll";
$query = $con->prepare($sql);
$query->bindparam(':roll', $roll[$key]);
$query->bindparam(':name', $name[$key]);
$query->execute();
}
}
答案 0 :(得分:1)
如何在循环外准备语句,然后在循环中绑定值并执行。
<?php
if(isset($_POST['submit'])){
$name = $_POST['name'];
$roll = $_POST['roll'];
$sql = "UPDATE student SET name=:name WHERE roll=:roll";
$query = $con->prepare($sql);
foreach($roll as $key => $n){
$query->bindParam(':roll', $n[$key]);
$query->bindParam(':name', $name[$key]);
$query->execute();
}
}
答案 1 :(得分:-1)
对于此操作使用for循环,因为不涉及关联数组
if(isset($_POST['submit'])){
$name = array();// initialize it first for a good coding standard
$roll = array();// initialize it first for a good coding standard
$name = $_POST['name'];
$roll = $_POST['roll'];
for($i=0;$i<count($name);$i++){ // considering the array elements of roll are equal to name elements
$sql = "UPDATE student SET name=:name WHERE roll=:roll";
$query = $con->prepare($sql);
$query->bindparam(':roll', $name[$i]);
$query->bindparam(':name', $roll[$i]);
$query->execute();
}
}