PDO update table using array

喜欢而已 提交于 2020-04-07 09:35:06

问题


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 FORM

    <td>
        <input type="number" name="roll[]" value="<?php echo $roll?>">
    </td>
    <td>
        <input type="text" name="name[]" value="<?php echo $name?>">
    <td>

I can print data.

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";
        }
    }

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 CODE

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

回答1:


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



回答2:


Use for loop for this operation as there are no associative arrays involved

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


来源:https://stackoverflow.com/questions/48501067/pdo-update-table-using-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!