How to Update Multiple Rows in a MySQL Database Using a Single Form Submission?

Mary-Kate Olsen
Release: 2024-11-06 02:30:02
Original
647 people have browsed it

How to Update Multiple Rows in a MySQL Database Using a Single Form Submission?

Post Form and Update Multiple Rows with MySQL

In this scenario, we aim to create a form that enables backend users to modify the titles and tags of multiple photos associated with a specific gallery. After form submission, these changes should be applied simultaneously to all selected rows in the database.

Form Structure

The provided code grabs photos from the database using the gallery ID and displays them as a form with input fields for title and tags. These fields are linked to hidden inputs containing the photo ID.

// Fetch photos from the database
$result = $db->prepare("SELECT * FROM photos WHERE gallery_id = :gallery_id ");
$result->bindParam(':gallery_id', $id);
$result->execute();

// Generate input fields for each photo
echo '<form action="" method="POST">';
echo "<ul id='photos'>";

for ($i = 0; $row = $result->fetch(); $i++) {
    // Get photo details
    $id = $row['id'];
    $title = $row['title'];
    $tags = $row['tags'];
    $src = $row['src'];

    // Create input fields
    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 />"; // ***** Adjusted the array submission *****
    echo "<input type='text' name='photo_tags[]' value='$tags' /><br />"; // ***** Adjusted the array submission *****
    echo "<input type='hidden' name='photo_id[]' value='$id' />"; // ***** Adjusted the array submission *****
    echo "</li>";
}

echo "</ul>";
echo '<div style="clear:both"></div>';
Copy after login

The above is the detailed content of How to Update Multiple Rows in a MySQL Database Using a Single Form Submission?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!