[英]delete row php&mysql dynamique link
I want to make a link to delete a record from database using dynamic links with php however i couldn't figure it out this is my code : 我想建立一个链接,使用php动态链接从数据库中删除一条记录,但是我不知道这是我的代码:
<?php
$query = "SELECT * FROM posts ";
$result = mysqli_query($connect, $query);
?>
<table>
<tr style="background: #afafaf;">
<th>Id</th>
<th>Title</th>
<th>Action</th>
</tr>
<?php
while($rows = mysqli_fetch_assoc($result)){
echo "<tr>";
echo "<td class=\"center\">".$rows['id']."</td>";
echo "<td>".$rows['title']."</td>";
echo "<td><a href=\"delete_post.php?id=".$rows['id']."\"> delete</a></td>";
echo "</tr>";
}
?>
</table>
the output link would be like .../delete.php?id=X
can anyone help me write the code for delete.php
? 输出链接就像
.../delete.php?id=X
谁能帮我写出delete.php
的代码吗?
Have the below code in your page. 在页面中输入以下代码。 This first checks if
$_GET['id']
is set. 这首先检查
$_GET['id']
是否设置。 It will only run if it is, that way you don't get Undefined Index error. 它只会在运行的情况下运行,这样您就不会收到未定义索引错误。
<?php
if (isset($_GET['id'])) {
$deleteId = htmlspecialchars($_GET['id'], ENT_QUOTES);
$delete = "DELETE FROM `posts` WHERE `id` = " . $deleteId;
}
?>
I also used htmlspecialchars
to sanitize the user input. 我还使用
htmlspecialchars
清理用户输入。 You could run some validation using ctype_digit
to ensure that the input is actually an integer. 您可以使用
ctype_digit
运行一些验证,以确保输入实际上是整数。
I suggest using prepared statement in MySQLi to prevent SQL injection. 我建议在MySQLi中使用预处理语句来防止SQL注入。
Edit 1 编辑1
Example with ctype_digit
. ctype_digit
示例。 This checks if the id
is set and if it is a number, technically you could just use ctype_digit
because if id
is empty then ctype
will return false as var_dump(ctype_digit(""));
这将检查是否设置了
id
,是否为数字,从技术上讲,您可以使用ctype_digit
因为如果id
为空,则ctype
将返回false作为var_dump(ctype_digit(""));
will return false
, with that logic in mind, the value must be set for ctype_digit
to work and it must be an integer. 将返回
false
,牢记这一逻辑,必须将值设置为ctype_digit
才能起作用, 并且该值必须为整数。
<?php
if (ctype_digit($_GET['id'])) {
$deleteId = htmlspecialchars($_GET['id'], ENT_QUOTES);
$delete = "DELETE FROM `posts` WHERE `id` = " . $deleteId;
}
?>
That would be something like this: 那将是这样的:
$deleteId = $_GET['id'];
$sql = "DELETE FROM posts WHERE id = ".$deleteId;
Remember to escape your variables before sending them off to the MySQL server. 请记住在将变量发送到MySQL服务器之前先对其进行转义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.