【发布时间】:2020-01-03 15:37:30
【问题描述】:
我想从 SQL-DB 中列出一些产品,它运行良好。现在用户应该点击两个不同的按钮来为这个特定产品的数量加上 +1 并减去 -1。
这就是我的前端的样子:
<?php
require_once('../system/config.php');
require_once('../system/server.php');
// Create connection
$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT item, count, date FROM shop";
$result = $conn->query($sql);
?>
[...]
<form>
<table>
<form method="post" action="frontend.php">
<tr>
<th></th>
<th></th>
<th>Amount</th>
<th>Item</th>
<th>Date</th>
<th></th>
</tr>
<?php while($row = mysqli_fetch_array($result)):?>
<tr>
<td><button class="delete" name="delete">x</button></td>
<td><button class="minus" name="minus">-</button></td>
<td><?php echo $row['count'];?></td>
<td><?php echo $row['item'];?></td>
<td><?php echo $row['date'];?></td>
<td><button class="plus" name="plus">+</button></td>
</tr>
</form>
<?php endwhile;?>
</table>
</form>
到目前为止,这里的所有内容都有效,它列出了数据库中的数据。
对于我的后端代码,我认为我将使用“更新”。我只发布了一个功能,其他两个非常相似。
$db = mysqli_connect('xxx', 'xxx', 'xxx', 'xx');
//Item add
if (isset($_POST['plus'])) {
$count = mysqli_real_escape_string($db, $_POST['count']);
$query = "UPDATE `shop` SET `count` = `count` + 1 WHERE `id` = '51'";
mysqli_query($db, $query) or die(mysqli_error($db));
header('location: frontend.php');
};
如果我提供一个特定的 ID 号,它就会起作用。如果我希望更改的 ID 是单击按钮所在的列的 ID,我该怎么办?
【问题讨论】:
-
在代码中使用
die(mysqli_error($conn));是一个非常糟糕的主意,因为它可能会泄露敏感信息。更多解释见这篇文章:mysqli or die, does it have to die? -
您需要将ID连同按钮一起发送。
-
您应该在表单中添加一个隐藏字段以传递您要执行操作的 id。您还应该更改您的选择以包含上述 id。
-
<form>里面的<form>没用。 -
我不认为
form可以是孩子table