在删除父数据之前检查子数据是否存在

时间:2019-05-29 06:23:22

标签: php html

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

DELETE.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;
       }
   }

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

1 个答案:

答案 0 :(得分:2)

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

类似这样的东西:

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

要在其中显示消息文本的地方。