php - 在删除父级之前检查子级数据是否存在
问题描述
我有 news_Category 和 news 表,这里每条新闻都属于一个类别,所以在删除 new_category 之前,我想向用户显示一个消息,表明该类别中存在子新闻,因此您不允许删除,如果没有子新闻,请确认提醒用户“你真的想删除吗”。如果他确认新闻类别被删除。
HTML 的东西
<?php echo "<a style='color:red;''
href='delete.php?delete=$values[category_id]&
img=$values[category_image]'><i class='fas fa-trash-alt'></i></a>"; ?>
if ($_GET['msgError']) {
echo "<script>alert('First Delete The News Than Category');</script>";
}
if ($_GET['msg']) {
?>
<?php
}
?>
删除.PHP
if (isset($_GET['delete'])) {
$id= $_GET['delete'];
$img=$_GET['img'];
$obj=new commands();
$obj->delete_category($id,$img);
}
删除功能
function delete_category($id,$img)
{
$stmt = $this->con->prepare("SELECT category_id FROM nm_news where category_id='$id'");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($result) {
header('Location: news_category.php?msgError=' . urlencode(base64_encode("First Delete The News Than Category")));
} else {
$sql = $this->con->prepare("DELETE FROM `nm_category` WHERE category_id=:id");
$sql->bindParam(':id', $id);
$sql->execute();
unlink("uploads/" . $img);
header('Location: news_category.php?msg="confirm"');
$this->con = null;
}
}
我无法在这里进行逻辑,如何检查子新闻是否存在以便我可以显示错误消息以及如果没有子新闻如何显示确认警报以允许删除
解决方案
您需要检查结果是否为空。
像这样的东西:
function delete_category($id,$img)
{
$stmt = $this->con->prepare("SELECT category_id FROM nm_news where category_id='$id'");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (empty($result)) {
header('Location: news_category.php?msgError=' . urlencode(base64_encode("First Delete The News Than Category")));
} else {
$sql = $this->con->prepare("DELETE FROM `nm_category` WHERE category_id=:id");
$sql->bindParam(':id', $id);
$sql->execute();
unlink("uploads/" . $img);
header('Location: news_category.php?msg="confirm"');
$this->con = null;
}
}
由于额外的详细信息请求而编辑
在前端,您只需要像这样显示 GET msgError:
<?php isset($_GET['msgError']) ? echo url_decode(base64_decode($_GET['msgError'])) : '' ?>
要显示消息文本的位置。
推荐阅读
- vue.js - 如何在点击时更改 Vuejs v-for 循环中的前置图标?
- python-3.x - Pandas,BeautifulSoup - 迭代和编写多个页面以实现卓越
- css - React Router 似乎阻止了自定义 CSS
- ios - 如果 memorylayout<>.stride 和 memorylayout<>.size 不同,则无法构建?
- elixir - 如何在不经过常规登录过程的情况下使用 Wallaby 登录用户?(设置 cookie/会话)
- spring - Spring Boot REST API 版本控制的自定义标头方法
- javascript - 用 JavaScript 解释以下代码的输出,这似乎与预期不同
- python - 如何在 Python 中使用 concurrent.futures 避免附加错误?
- python - 如何将值添加到字典中的特定列表?
- flutter - 如何将 TabBarView 与 BLoC 一起使用?