简体   繁体   中英

update multiple MySQL rows at once

I have this PHP Code that selects rows from a database and puts the data in form fields:

$global_sql2="SELECT name, field, value FROM global_settings";
$global_rs2=mysql_query($global_sql2,$conn) or die(mysql_error());
while($global_result2=mysql_fetch_assoc($global_rs2))
{
    echo '<tr>
                <td><strong>'.$global_result2["name"].'</strong></td>
                <td><input type="text" name="'.$global_result2["field"].'" size="50" value="'.$global_result2["value"].'" /></td>
            </tr>';
}

then this PHP code on the submit page:

$global_sql3="SELECT name, field, value FROM global_settings";
$global_rs3=mysql_query($global_sql3,$conn) or die(mysql_error());
while($global_result3=mysql_fetch_assoc($global_rs3))
{
    if($_POST[$global_result3["field"]] != $global_result3["value"])
    {
        $sql="UPDATE global_settings set value = '".$_POST[$global_result3["field"]]."' where field = '".$global_result3["field"]."' ";
        $rs=mysql_query($sql,$conn) or die(mysql_error());
        echo '<h3><font color="#FF0000">'.$global_result3["name"].'</font> Successfully Updated to <font color="#FF0000">'.$_POST[$global_result3["field"]].'</font></h3>';
    }
}

i want to be able to update more than just one field - the above works fine for just the value column in the database but i want to be able to do 5 columns

how can i do this?

PS: Im not worried about SQL Injection as this code is not public

What you are looking for then is setting the columns using the comma delimited field names:

UPDATE `tableName` SET `field1` = 'value', `field2` = 'value', `field3` = 'value' WHERE `field` = 'fieldname';

If you want to update multiple rows with different values within 1 query you will need to use case statements. A quick google search returned a pretty straight forward tutorial here

UPDATE mytable
    SET field1 = CASE mainField
        WHEN mainFieldName1 THEN 'value'
        WHEN mainFieldName2 THEN 'value'
        WHEN mainFieldName3 THEN 'value'
    END,
    field2 = CASE mainField
        WHEN mainFieldName1 THEN 'New Title 1'
        WHEN mainFieldName2 THEN 'New Title 2'
        WHEN mainFieldName3 THEN 'New Title 3'
    END
WHERE mainField IN (mainFieldName1,mainFieldName2,mainFieldName3)

Even if you don't care about SQL injection, you should be learning best practices not to mention PDO has a nicer, cleaner OO syntax. You can use use a single page for this too rather than a separate PHP file.

Mixing SQL, PHP and HTML all together in close proximity isn't easy on the eyes and doesn't maintain well. I've written some small helper functions to promote reusability and readability.

<?php

$dbh=false;

//Connect to your DB with PDO, only create the connection once
function getDbConnection() {
    global $dbh;
    $dbh = $dbh ? $dbh : new PDO('mysql:host=127.0.0.1;dbname=myDb', 'root', '');
    return $dbh;
}

function getSettings(){
    return getDbConnection()->query('SELECT * from global_settings');
}

function updateSettings(){
    foreach($_POST['settings'] as $key => $value){
        //Use a prepared statement with named parameters
        $query = getDbConnection()->prepare('UPDATE global_settings set value=:value WHERE field=:field');
        //Use named params to mitigate security issues
        $query->bindParam(':value', $value);
        $query->bindParam(':field', $key);
        $query->execute();
    }
}

// Has the form been submitted?
if(isset($_POST['settings']))
    updateSettings();

?>

<form action="" method="post">
    <table>
        <?php foreach(getSettings() as $setting): ?>
        <tr>
            <td>
                <label><?= $setting['field'] ?></label>
                <input type="text" name="settings[<?= $setting['field'] ?>]" size="50" value="<?= $setting['value'] ?>" />
            </td>
        </tr>
        <?php endforeach; ?>
    </table>
    <input type='submit' />
</form>

This is based on the following DB schema:

数据库架构

And you will get a form like this:

形成

There's a good PDO starter here: http://net.tutsplus.com/tutorials/php/php-database-access-are-you-doing-it-correctly/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM