Search code examples
phpmysql

Post form and update multiple rows with mysql


I have searched all over this website, but not yet found the answer for this. Pr maybe I am not able to apply it correctly. I have a form that grabs all photos with a certain GALLERY_id attached to it. The backend user can then change the title of the photo and change the tags. After submitting the form the query should update all rows. Here is what I have so far which does not doe anyting:

THE FORM

if(isset($_GET['id']))
{

    $id=$_GET['id'];
    $result = $db->prepare("SELECT * FROM photos WHERE gallery_id = :gallery_id ");      
    $result->bindParam(':gallery_id', $id);
    $result->execute();

    echo '<form action="" method="POST">';
    echo "<ul id='photos'>";

    for ($i = 0; $row = $result->fetch(); $i++)
    {

        $id = $row['id'];
        $title = $row['title'];
        $tags = $row['tags'];
        $src = $row['src'];

        echo "<li><a class='lightbox' href='images/$src'><img src='images/$src' id='$id' alt='$title' /></a><br />";
        echo "<input type='text' name='photo_title' value='$title' /><br />";
        echo "<input type='text' name='photo_tags' value='$tags' />";
        echo "<input type='hidden' name='photo_id' value='$id' />";
        echo "</li>";
    }

    echo "</ul>";

}

?>
<div style="clear:both"></div>
<input type="submit" name="changeTitle" value="Save"/>
</form>

UPDATE QUERY

if (isset($_POST['changeTitle']))
{
    foreach ($_POST as $p)
    {
        $id=$p['photo_id'];
        $title=$p['photo_title'];
        $tags=$p['photo_tags'];


        $sql = "UPDATE photos SET title=?, tags=? WHERE id=?";
        $query = $db->prepare($sql);
        $query->execute(array($title, $tags, $id));

    }
}

Solution

  • Since you have multiple html fields with same names, you have to submit them as an arrays:

    echo "<input type='text' name='photo_title[]' value='$title' /><br />";
    echo "<input type='text' name='photo_tags[]' value='$tags' />";
    echo "<input type='hidden' name='photo_id[]' value='$id' />";
    

    After submitted, loop through any array variable like

    $sql = "UPDATE photos SET title=?, tags=? WHERE id=?";
    $query = $db->prepare($sql);
    
    foreach ($_POST['photo_id'] as $key => $photo_id) {
        $title = $_POST['photo_title'][$key];
        $tags = $_POST['photo_tags'][$key];
    
        $query->execute([$title, $tags, $photo_id]);
    }