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

DDD
Release: 2024-11-05 14:59:02
Original
404 people have browsed it

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

Post Form and Update Multiple Rows with MySQL

Issue:

You have created a form that retrieves all photos with a specific gallery ID and allows users to update their titles and tags. However, the current code is not updating any rows in the database.

Form Structure:

The form generates an HTML list of photos, with input fields for updating their titles, tags, and hidden fields for identifying their IDs.

Update Query:

The update query iterates over each submitted form and executes a separate UPDATE statement for each photo. However, as coded, the query is not able to access the form data correctly.

Solution:

To successfully update multiple rows, you need to submit the form data as arrays and loop through them in the update query.

Form Update:

Modify the input fields to submit values as 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' />";
Copy after login

Update Query Rewrite:

Iterate through the submitted form data arrays:

foreach ($_POST['photo_id'] as $key => $photo_id) {
    $id = $photo_id;
    $title = $_POST['photo_title'][$key];
    $tags = $_POST['photo_tags'][$key];

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

This updated code will correctly loop through the submitted form data, extract the updated values, and execute the UPDATE statement for each photo, successfully updating multiple rows in your MySQL database.

The above is the detailed content of How to Update Multiple Rows in a MySQL Database Using a Form?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template