简体   繁体   中英

PDO update table using array

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM