在一个查询中更新整个表

时间:2017-12-05 15:02:50

标签: php mysql

如果有重复的话题 - 请原谅我,但我还没有找到解决方案。首先,我有一个php文件(update.php)。该文件包含:

<form action='update.php' method='post'>
<table border='1'>
    <?php
        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "exchange";
        $conn = new mysqli($servername, $username, $password, $dbname);
        if (mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }
        mysqli_set_charset($conn,"utf8");
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
        $sql = "SELECT ID, name, symbol, buy, sell FROM exchangevalues";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                echo "<tr>";
                echo "<td><input type='text' name='ID' value='".$row["ID"]."'>";
                echo "<td>".$row["name"]."</td>";
                echo "<td>Buy: <input type='text' name='buy' value='".$row['buy']."'></td>";
                echo "<td>Sell: <input type='text' name='sell' value='".$row['sell']."'></td>";
                echo "</tr>";
            }
        }
        $conn->close();
    ?>
<table>

我的数据库中有14行和5列。如何使用新值更新'click'和'sell'列中的每一行?'click'(isset submit button)?我尝试过ID [],买[],但我遇到循环问题,我无法处理它。我在localhost上运行MySQL,我也知道只有最后一行会在没有运行循环的情况下更新,但仍然...

1 个答案:

答案 0 :(得分:0)

我假设您有相应的PHP代码来处理输入,以下是创建表单时HTML需要做的示例:

if ($result->num_rows > 0) {
    $i=0;
    while($row = $result->fetch_assoc()) {
        echo "<tr>";
        echo "<td><input type='text' name='ID[" . $i . "]' value='".$row["ID"]."'>";
        echo "<td>".$row["name"]."</td>";
        echo "</tr>";
        }
    }

在php端处理输入,你可以这样做:

$id_array = $_REQUEST["ID"];
foreach($id_array as $id){
    //do insert with $id 
}