首页 > 解决方案 > 在删除父级之前检查子级数据是否存在

问题描述

我有 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;
       }
   }

我无法在这里进行逻辑,如何检查子新闻是否存在以便我可以显示错误消息以及如果没有子新闻如何显示确认警报以允许删除

标签: phphtml

解决方案


您需要检查结果是否为空。

像这样的东西:

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'])) : '' ?>

要显示消息文本的位置。


推荐阅读