gpt4 book ai didi

PHP & MySQL 更新查询只更新表中的最后一条记录

转载 作者:搜寻专家 更新时间:2023-10-30 19:57:56 25 4
gpt4 key购买 nike

我有一个 HTML 表单,我用它通过后脚本更新 MySQL 表 - 但是,我遇到了一个问题,即每行上的更新按钮只对表中的最后一行有效。

<?php

$link = mysql_connect ('localhost', 'root', 'password');
mysql_select_db ('cardatabase');

$select = 'SELECT * from cars';
$result = mysql_query($select, $link);

if(isset($_POST['update'])){
$updatequery = "UPDATE cars SET
ID='$_POST[id]',
CARMAKE='$_POST[carmake]',
CARMODEL='$_POST[carmodel]',
FUELTYPE='$_POST[fueltype]',
TRANSMISSION='$_POST[transmission]',
DOORS='$_POST[doors]',
AMOUNT='$_POST[amount]',
AVAILABLE='$_POST[available]'
WHERE ID='$_POST[hidden]'";

mysql_query($updatequery, $link);
};

echo '<table><form action=update.php method=post>';
echo '<tr><td>ID</td><td>Make</td><td>Model</td><td>Fuel Type</td><td>Transmission</td><td>Engine Size</td><td>Doors</td><td>Amount</td><td>Available</td></tr>';



while($row = mysql_fetch_array($result)) {
echo '<tr>';
echo "<td><input type='text' name='id' value='{$row['ID']}'</td>";
echo "<td><input type='text' name='carmake' value='{$row['CARMAKE']}'</td>";
echo "<td><input type='text' name='carmodel' value='{$row['CARMODEL']}'</td>";
echo "<td><input type='text' name='fueltype' value='{$row['FUELTYPE']}'</td>";
echo "<td><input type='text' name='transmission' value='{$row['TRANSMISSION']}'</td>";
echo "<td><input type='text' name='enginesize' value='{$row['ENGINESIZE']}'</td>";
echo "<td><input type='text' name='doors' value='{$row['DOORS']}'</td>";
echo "<td><input type='text' name='amount' value='{$row['AMOUNT']}'</td>";
echo "<td><input type='text' name='available' value='{$row['AVAILABLE']}'</td>";
echo "<td><input type='hidden' name='hidden' value='{$row['ID']}'</td>";
echo '<td><input type="submit" name="update" value="Update"</td>';
echo '</tr>';
}

echo '</form></table>';
mysql_close ($link);

汽车表:

MySQL table

最佳答案

为了可见性,让我们从这个开始:

For future users seeing your questions. If you know this, great! Welcome to Stack Overflow! Please, don't use mysql_* functions in new code. They are no longer maintained and the deprecation process has begun on it. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.


您遇到的问题是由于为所有输入赋予相同的名称(idcarmake 等)引起的。这意味着只会提交最后一行。

给他们这样的名字:

name="id[]"

这将使 PHP 将 $_POST 值视为数组,并且您可以访问

$_POST["id"][3]

以获取第四行(从0开始)为例。

关于PHP & MySQL 更新查询只更新表中的最后一条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13728744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com