0

我无法使此功能正常工作。这是我的数据库设计

我正在一个应用程序中工作,其中当用户删除父类别时,所有子类别也将被删除,等等等等。例如:

当用户在我的应用程序中单击“Test1”类别时,“Test1.1”和“Test1.1.1”将被删除,因为它位于“Test1”类别下。

在此处输入图像描述

这是我的数据库设计(上图)。

这是我写的代码:

function DeleteProjectPhotos( $cat_id ) {
        $sql = "SELECT * FROM project_category WHERE category_id = '$cat_id'"; 
        $query = mysql_query( $sql ) or die( mysql_error() );
        if( mysql_num_rows( $query ) > 0 ) {
            $sql = "SELECT * FROM project_category WHERE parent_id = '$cat_id'"; 
            $query = mysql_query( $sql ) or die( mysql_error() );
            if( mysql_num_rows( $query ) > 0 ) {
                while( $row = mysql_fetch_assoc( $query ) ) {
                    $this->DeleteProjectPhotos( $row['category_id'] );
                }
            } else {
                $sql = "DELETE FROM project_category WHERE category_id = '$cat_id'";
                $query = mysql_query( $sql ) or die( mysql_error() );
            }
        }
    }

但我认为这里的整个逻辑是错误的,因为当我尝试删除 category_id 33 时,所有内容都不会被删除。请教我如何做这个。

您的帮助将不胜感激和奖励!

谢谢!:)

4

2 回答 2

1
<?php

$catID = $_GET['catID']; 
deleteCategory($catID);

function connect(){

  $host = 'localhost';
  $dbName = 'sony';
  $userName = 'root';
  $password = '';

  $conn = new PDO("mysql:host=$host;dbname=$dbName",$userName,$password);
  $conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

  return $conn;
  }

  $stmt = '';
 function deleteCategory($catID){

  $conn = connect();
  $tableName = 'childparent';

  $sql = "select catID from $tableName where parentID = :catID";

  global $stmt;
  $stmt = $conn->prepare($sql);


      $idsToDelete = getChilds($catID);
      $idsToDelete[] = $catID;
  //print_r($idsToDelete);

  $delExp = '';
  foreach($idsToDelete as $id)
     $delExp .= " catID=$id or";
  $delExp = preg_replace('/or$/','',$delExp);

  if($delExp != ''){

      $delSql = "delete from $tableName where $delExp";
      //echo $delSql;

       $delStmt = $conn->prepare($delSql);
       $delStmt->execute(); 

      }






  }

 $collectedIDs = array();

 function getChilds($catID){

 global $stmt,$collectedIDs;

 $stmt->bindValue(':catID',$catID);

 $stmt->execute();

 $childCatIDs = array();
 while($row = $stmt->fetch(pdo::FETCH_ASSOC)){

    $childCatIDs[] = $row['catID'];
    $collectedIDs[] = $row['catID'];    
 }

 //print_r($childCatIDs);
 //die();
 if(!empty($childCatIDs)){
        foreach($childCatIDs as $cid)
            getChilds($cid);

 }

 return $collectedIDs;


  }



?>
于 2012-05-27T18:00:54.903 回答
-1

如果你不想要触发器,你可以在删除类别上尝试http://php.net/manual/en/function.mysql-affected-rows.php你得到它的 id 并且有一个返回你尝试删除按类别或父母

于 2012-05-27T16:41:30.887 回答