Home >Database >Mysql Tutorial >How to Efficiently Update Multiple MySQL Rows from a Single HTML Form?

How to Efficiently Update Multiple MySQL Rows from a Single HTML Form?

DDD
DDDOriginal
2024-12-01 18:32:11516browse

How to Efficiently Update Multiple MySQL Rows from a Single HTML Form?

Submitting and Updating Multiple Rows in MySQL

Problem:

You have a form that collects data for multiple photo records, allowing the user to edit their titles and tags. The goal is to update all selected records in the database.

Form Structure:

Within the form, you have fields for each photo record:

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

Update Query:

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>

Solution:

Instead of using individual input fields with the same names, you should use arrays in the form fields. This allows you to capture multiple values and iterate through them in the POST data. Then, you can update each row individually using a prepared statement and the array values.

This approach ensures that all selected records are updated with the new title and tag values.

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

Statement:
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