cell-in
cell-in

Reputation: 789

Mysql query is working but doesn't enter the loop, PHP,MYSQL

I have one table on my database that includes kategoriID,kategoriAd,kategoriEbeveyn. It is like categoryID,catagoryName and categoryParent.

I want that happens that is when i try to delete main category, I can delete main category and sub categories.

-World

............ +Europe

....................... *Turkey

.................................**Istanbul

When I try to delete, This function works for World and Europe. But Turkey and Istanbul is still in my database. I couldn't delete those because of the error.

"mysql_fetch_array() expects parameter 1 to be resource, boolean given in"

| kategoriID | kategoriAd | kategoriEbeveyn |

| 1 | World | 0 |

| 2 | Europe | 1 |

| 3 | Turkey | 2 |

| 4 | Istanbul | 3 |

Here is my function.

<?php

function KategoriVeAltKategorileriSil(){
$kategoriID = $_GET['kategoriID'];
     mysql_query("DELETE FROM kategoriler WHERE kategoriID = ' $kategoriID '") or die (mysql_error());
       $delete = mysql_query("DELETE FROM kategoriler WHERE kategoriEbeveyn = ' $kategoriID ' ") or die (mysql_error());        

    if($delete){
         while($silinecek = mysql_fetch_array($delete)){

               KategoriVeAltKategorileriSil($silenecek[' kategoriID ']);
             echo mysql_error();
                     }
    echo "Kategori ve alt kategorileri silindi.";
    }else{ echo "Silme işlemi gerçekleştirilemedi!" .mysql_error(); }
        }

?>

Or Do i need to use Trigger?

Upvotes: 2

Views: 170

Answers (3)

Markus Deibel
Markus Deibel

Reputation: 1329

Well, the point is that you have a tree structure that is mapped to the flat (row) structure of the DB.

You will need to handle this with a recursive delete method.

Your code should probably look something like:

function DeleteCategory(catId)
{
    GetChildCategoriesOf(catId)

    if (num_rows > 0)
    {
         foreach(ChildCategoryFound)
         {
              DeleteCategory(ChildCatId); //Recursive call
         }
    }

    Delete(catId) //Delete the parent as last action
}

Upvotes: 0

Nanhe Kumar
Nanhe Kumar

Reputation: 16297

    function deleteCategory($kategoriID) {
        $result=mysql_query("SELECT * FROM kategoriler WHERE kategoriEbeveyn='$kategoriID'");
        if (mysql_num_rows($result)>0) {
             while($row=mysql_fetch_array($result)) {
                  deleteCategory($row['kategoriID']);
             }
        }
        mysql_query("DELETE FROM kategoriler WHERE kategoriID='$kategoriID'");
    }

you can use this recursive function

Upvotes: 4

JoDev
JoDev

Reputation: 6873

The best way would be to make a request like :

DELETE FROM kategoriler WHERE ketegoriID IN (SELECT kategoriID
FROM kategoriler
WHERE kategoriID = ' $kategoriID ' or kategoriEbeveyn = ' $kategoriID ');

of course it's not complete because i don't know your databases structure

Upvotes: 0

Related Questions