PDO: defining parameters using foreach and $_POST

前端 未结 1 1829
野的像风
野的像风 2021-01-24 01:01

I\'m trying to create a page that allows users change their info in a sql database using PDO. I\'m new to this and I\'m running into an error. I\'m using this as a source: http:

相关标签:
1条回答
  • 2021-01-24 01:29

    I have simplified the code to illustrate how to create dynamic UPDATE query. This uses "lazy" binding and regular placeholders ?.

    The text inputs are set as a regular array (ie. not associative) of values.

    <?php
    if(isset($_POST['submit'])){
        if (isset($_POST["info"]) && !empty($_POST["user_id"])) {
            $query = "UPDATE `users` SET ";
            $query_params = array();
            $i =1;
            foreach ($_POST['info'] as $value) {
                // push array with each valid info entry ...
                if ($value) {
                    $query .= "`info".$i. "` = ?,"; 
                    array_push($query_params,$value);
                }
                $i++;
            }
            $query = rtrim($query, ',');//remove trailing ,
            //  
            $query .= " WHERE `id` = ?"; 
            array_push($query_params,$_POST['user_id']);
            //Show query and parameter array Remove after testing
            echo $query;    
            echo "<br>";
            print_r($query_params);
            // Execute the query
            $stmt = $db->prepare($query);
            $result = $stmt->execute($query_params);
        }
    }
    ?>
    <form method="POST" action="#">
    <input type="text" name="info[]" id="info" value=""> 
    <input type="text" name="info[]" id="info"  value="">
    <input type="text" name="info[]" id="info"  value="">
    <input type="text" name="info[]" id="info" value="">
    <input type="text" name="user_id" id="user_id" value="">
    <input type="submit" name="submit" value="Submit">
    

    Typical result

    UPDATE `users` SET `info1` = ?,`info2` = ? WHERE `id` = ?
    Array ( [0] => john [1] => smith [2] => johnsmith ) 
    
    0 讨论(0)
提交回复
热议问题