这个问题非常基础,我在stackoverflow中发现了许多类似的问题,但没有一个能适合我。
我设计了一个显示如下数据的表:
ID name Delete
1 abc Delete
2 def Delete
用于上述显示的代码是
<?php
$con=mysqli_connect("abc","abc","abc","abc");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM student");
echo "<table class='table table-striped table-bordered table-hover'>
<thead>
<tr>
<th>ID</th>
<th>name</th>
<th>delete</th>
</tr>
</thead>";
while($row = mysqli_fetch_array($result))
{
echo "<tbody data-link='row' class='rowlink'>";
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td><a href='delete.php'>Delete</a></td>";
echo "</tr>";
echo "</tbody>";
}
echo "</table>";
mysqli_close($con);
?>
delete.php的代码
<?php
$con=mysqli_connect("abc","abc","abc","abc");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"DELETE FROM student WHERE id='$id'");
mysqli_close($con);
header("Location: index.php");
?>
数据库视图
Id name
1 abc
2 cdf
问题是它没有删除数据,也没有显示任何错误
我是这个领域的新手,如果有人能帮助我,我将不胜感激。
答案 0 :(得分:5)
更改此行:
echo "<td><a href='delete.php'>Delete</a></td>";
到
echo "<td><a href=\"delete.php?id=".$row['id']."\">Delete</a></td>";
然后对于 delete.php (并且最初在评论中说明,$id
未定义)。
<?php
$con=mysqli_connect("abc","abc","abc","abc");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_GET['id']; // $id is now defined
// or assuming your column is indeed an int
// $id = (int)$_GET['id'];
mysqli_query($con,"DELETE FROM student WHERE id='".$id."'");
mysqli_close($con);
header("Location: index.php");
?>
它会起作用。
然而,出于安全考虑,您应该考虑使用mysqli
with prepared statements或PDO with prepared statements,更安全。我在下面列举了一个例子。
以下是准备好的陈述示例:
<?php
$DB_HOST = "xxx";
$DB_NAME = "xxx";
$DB_USER = "xxx";
$DB_PASS = "xxx";
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($con->connect_errno > 0) {
die('Connection failed [' . $con->connect_error . ']');
}
$id = (int)$_GET['id'];
$update = $con->prepare("DELETE FROM student WHERE id = ?");
$update->bind_param('i', $id);
$update->execute();
$update->close();
答案 1 :(得分:0)
在您的链接中添加GET
参数:
echo "<td><a href='delete.php?id='".$row['id']."'>Delete</a></td>";
然后在delete.php
查询中抓住它:
$id = $_GET['id'];
mysqli_query($con,"DELETE FROM student WHERE id='".$id."'");
答案 2 :(得分:-1)
您可能不希望每次删除行时都刷新页面,您可以使用ajax请求更快地执行此操作。您可以从以下链接获取完整代码:delete individual row from databse using ajax