gpt4 book ai didi

php - 使用php删除表的特定行

转载 作者:可可西里 更新时间:2023-11-01 07:58:47 24 4
gpt4 key购买 nike

我设计了一个表格来显示如下数据:

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");
?>

数据库 View 是

Id  name
1 abc
2 cdf

问题是它没有删除数据,也没有显示任何错误

最佳答案

注意根据HTTP standard , GET 方法不应用于修改数据库中的数据。因此,您应该使用带有 method="POST" 的表单,例如

echo '<td><form method="POST" action="delete.php"><input type="hidden" value="'.$row['id'].'"><input type="submit" value="Delete"></form></td>';

然后对于 delete.php,为了安全起见,您应该考虑使用 mysqli with prepared statements , 或 PDO with prepared statements它们更安全。我在下面包含了一个示例。


这是一个准备好的语句示例:

<?php 
$DB_HOST = "xxx";
$DB_NAME = "xxx";
$DB_USER = "xxx";
$DB_PASS = "xxx";

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);

$id = (int)$_POST['id'];

$update = $con->prepare("DELETE FROM student WHERE id = ?");
$update->bind_param('i', $id);
$update->execute();

关于php - 使用php删除表的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26107666/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com