我正在做一个学校项目。
该项目的意思是我创建了一个login/registration form
,
我可以在其中注册,登录和查看记录。
但是我还需要创建一个下拉菜单,以便我可以看到所有记录(用户),并且在其下方我需要创建一个按钮,当我选择一个记录/用户并按下Delete按钮时,需要从中删除数据库。而且我不知道该怎么做。
这是我的代码:
<?php
include(“ connectie.php”); 包括(“ deletecode.php”);
$conn = new mysqli("localhost", "student14_admin", "lol12345","student14_jordi");
mysqli_select_db($conn,'student14_jordi');
$sql = "DELETE FROM users WHERE ID='$_GET[id]'";
echo "<select name='user'>";
if ($result->num_rows>0) {
while($row = $result->fetch_assoc()) {
echo "<option value=" . $row['username'] . ">" . $row['username'] . "</option>";
}
}
echo "</select>";
?>
<form action="">
<a class="delete" href="delete.php?id=<?php echo $row['id']; ?>">Delete</a>
</form>
答案 0 :(得分:1)
创建一个按钮并将其命名为删除
<a class="delete" href="delete.php?id=<?php echo $row['id']; ?>">Delete</a>
然后创建一个delete.php文件,并在其中保存这些代码。
<?php include_once 'db_config_filename.php';
// get id value
$id = $_GET['id'];
// sql to delete a record
$sql = "DELETE FROM tablename WHERE id='$id'";
// print_r($sql);
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
}
else {
echo "Error deleting record: " . mysqli_error($conn);
}
//redirect here
include 'data.php';
?>
答案 1 :(得分:0)
我几乎可以正常工作了。我现在有了这段代码:
delete.php:
<?php
include ("connectie.php");
$sql = "SELECT * FROM users ";
$result = $conn->query($sql);
echo "<select name='user'>";
if ($result->num_rows>0) {
while($row = $result->fetch_assoc()) {
echo "<option value=" . $row['username'] . ">" . $row['username'] . "
</option>";
}
}
echo "</select>";
?>
<form action="" method="GET">
<input type="hidden" name="id" value=".$row['id']." />
<input type="submit" name="delete" value="verwijderen">
</form>
<?php
include ("deletecode.php");
?>
Deletecode.php:
<?php
$servername = "localhost";
$username = "student14_admin";
$password = "lol12345";
$dbname = "student14_jordi";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to delete a record
$sql = "DELETE FROM users WHERE id=3";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
这仅适用于记录3次事件。但是现在我需要确保,如果我从下拉菜单中选择一条记录,然后单击删除按钮,它需要从我的数据库中删除该记录。