在 PHP 中一次更新多行 [英] Update Multiple Rows at Once in PHP

查看:42
本文介绍了在 PHP 中一次更新多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Class 1"中显示学生的表格.用户可以更改信息并将其更新到数据库中.我想一次更新多行,但最终只更新了 1 行(最后一行).请帮助我.. 当我点击更新时,我应该如何更改代码以一次更新多行.谢谢.

I want to display table of student in "Class 1". User can change the information and update it into database. I want to update multiple rows at a time, but it ends up updating only 1 row (the last row). Please help me .. how should i change the code in order to update multiple rows at once, when i click on update. Thanks.

这是代码:

<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'test');

$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE) or die(mysql_error());
mysql_set_charset("utf8", $connection);
?>

    <form action='update.php' method='post'>
    <table border='1'>
        <?php
            $result = mysql_query("SELECT * FROM student WHERE class = 1 ");

                    echo "<tr>";
                        echo "<td colspan='3'>CLASS 1</td>";
                    echo "</tr>";

                    while($row = mysql_fetch_array($result)){

                    echo "<tr>";
                        echo "<td><input type='hidden' name='id' value='".$row['id']."' /></td>";
                        echo "<td>name  :<input type='text' name='name' value='".$row['name']."' /></td>";
                        echo "<td>Sex  :<input type='text' name='sex' value='".$row['sex']."' /></td>";
                        echo "<td>Age  :<input type='text' name='age' value='".$row['age']."' /></td>";
                    echo "</tr>";

            }

            echo "<input type='submit' name='update' value='UPDATE' />";
        ?>
    <table>
</form>

<?php

if(isset($_POST['update'])){
    $id  = $_POST['id'];
    $name= $_POST['name'];
    $sex = $_POST['sex'];
    $age = $_POST['age'];

    mysql_query("   UPDATE student
                       SET name= '$name', sex='$sex', age='$age'
                     WHERE id = '$id' ");   

    header("location: update.php");
    exit;
}   

?>

推荐答案

您需要使用输入数组.所以你的输入应该是这样的(注意 name 属性):

You need to use input arrays. So your inputs should look like this instead (notice the name attribute):

echo "<td>Sex  :<input type='text' name='name[]' value='".$row['name']."' /></td>";

然后在 PHP 中 $_POST['name'] 将是一个数组:

Then in PHP $_POST['name'] will be an array:

foreach($_POST['name'] as $name){

希望这有帮助...

这篇关于在 PHP 中一次更新多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆