使用数组的PDO更新表 [英] PDO update table using array

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

问题描述

我正在学习PDO并对此感到陌生.在PDO中使用数组会给我带来麻烦.我正在使用PDO语法开发简单的Web应用程序.一切进展顺利,但是我无法通过单个提交"按钮更新多个值.

I'm learning and new in PDO. The usage of array in PDO causes difficulty for me. I'm developing simple web application using PDO syntax. Everything is going on smoothly, but I can't update multiple values from single submit button.

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%错误,因此以下代码无法正常工作.请帮助如何使用数组更新

But I can't update multiple value at once. Perhaps it is because of lack of knowledge in terms of combination of array in PDO. I've searched in internet. But I found only advance question and answers. I can't found any example or discussion topics in this matter. I am sure I am 100% wrong, so following code doesn't work. Please help how to update using array

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();
    }
}

推荐答案

如何在循环外准备语句,然后在循环内绑定值并执行.

How about you prepare the statement outside the loop, then bind the values within the loop and execute.

<?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();
    }
}

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

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