PHP &MySQL 更新查询只更新表中的最后一条记录
我有一个 HTML 表单,我用它来通过 post 脚本更新 MySQL 表 - 但是,我遇到了一个问题,即每一行上的更新按钮只能用于表中的最后一行.
I have a HTML form which I am using to update a MySQL table via a post script - however, I am having an issue where the update buttons which are on each row only ever work for the last row in the table.
<?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);
cars
表:
为了可见性,让我们从这个开始:
Let's start with this for visibility:
为了将来的用户看到您的问题.如果你知道这一点,太好了!欢迎使用堆栈溢出!请不要在新代码中使用mysql_*
函数.它们不再维护,并且弃用过程已经开始.看到红框?了解准备好的语句,并使用PDO 或 MySQLi- 这篇文章 将帮助您决定哪个.如果您选择 PDO,这里有一个很好的教程.
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.
您遇到的问题是由于为所有输入提供相同的名称(id
、carmake
等)引起的.这意味着只会提交最后一行.
The problem you're experiencing is caused by giving all of your inputs the same names (id
, carmake
etc). This means only the last row would ever be submitted.
给他们起这样的名字:
name="id[]"
这将使 PHP 将 $_POST
值视为数组,您可以访问
That would make PHP treat the $_POST
values as arrays, and you can access
$_POST["id"][3]
例如获取第四行(从0开始).
To get the fourth row (Starting from 0), for example.