PDO update table using array

后端 未结 2 1746
北海茫月
北海茫月 2021-01-26 17:53

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

相关标签:
2条回答
  • 2021-01-26 18:16

    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();
    }
    }
    
    0 讨论(0)
  • 2021-01-26 18:25

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题