我无法使用此功能。这是我的数据库设计
我在一个应用程序中工作,当用户删除父类别时,所有子类别也将被删除,依此类推,等等。 例如:
当用户点击我的应用程序中的“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时,一切都不会被删除。请教我如何做到这一点。
您的帮助将受到高度赞赏和奖励!
谢谢! :)
答案 0 :(得分: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;
}
?>
答案 1 :(得分:-1)
如果你不想要触发器,你可以在删除类别上尝试http://php.net/manual/en/function.mysql-affected-rows.php,你会得到它的id,当你有一个返回时,你试图通过导演或父母删除