我正在使用SQL语句学习PHP,但在尝试创建删除按钮时遇到了问题。
问题是当我按下“删除”按钮时没有发生任何事情。 查询运行正常,它从循环中获取正确的用户ID。
<?php
require_once 'db_connect.php';
$select = "SELECT * FROM Users";
$result = mysqli_query($dbc, $select) or die('could not query database');
while ($row = mysqli_fetch_assoc($result)) {
echo '
<tr>
<td>' . $row['userid'] . '</td>
<td>' . $row['fnamn'] . ' ' . $row['enamn'] . '</td>
<td>' . $row['username'] . '</td>
<td>' . $row['email'] . '</td>
<td>' . '<form action="" method="post">
<input type="button" name="delete" value="Radera" />
</form>' . '</td>
</tr>';
if(isset($_POST['delete'])) {
$userid = $row['userid'];
$delete = "DELETE FROM Users WHERE userid = '$userid' ";
$result = mysqli_query($dbc, $delete) or die('could not query database');
}
}
mysqli_close($dbc);
?>
答案 0 :(得分:2)
你需要:
if (isset($_POST['delete']))
声明放在外面
在while
循环之前。这样的事情:
<?php
require_once 'db_connect.php';
if(isset($_POST['delete']) && isset($_POST['user_id'])) {
$userid = $_POST['user_id'];
$delete = "DELETE FROM Users WHERE userid = '$userid' ";
$result = mysqli_query($dbc, $delete) or die('could not query database');
}
$select = "SELECT * FROM Users";
$result = mysqli_query($dbc, $select) or die('could not query database');
while ($row = mysqli_fetch_assoc($result)) {
echo '
<tr>
<td>' . $row['userid'] . '</td>
<td>' . $row['fnamn'] . ' ' . $row['enamn'] . '</td>
<td>' . $row['username'] . '</td>
<td>' . $row['email'] . '</td>
<td>' . '<form action="" method="post">
<input type="hidden" name="user_id" id="user_id" value="'.$row['userid'].'" />
<input type="submit" name="delete" id="delete" value="Radera" />
</form>' . '</td>
</tr>';
}
mysqli_close($dbc);
?>
我建议您不要像上面那样直接将$_POST['user_id']
插入您的查询中;你会想要阅读准备好的陈述
答案 1 :(得分:1)
替换类型。
而不是:
<input type="button" name="delete" value="Radera" />
尝试:
<input type="submit" name="delete" value="Radera" />