Saturday, 7 September 2013

Related content - PHP - mysql

Related content - PHP - mysql

I'm currently developing a site from zero with PHP and mysql and found
that I can't think about a good way to solve this problem:

I want to be able to add, modify and delete some categories. These
categories will be printed in some other .php, that's not important. The
main problem is that I don't know how to put categories inside other
categories.
I've thought about creating a mysql table for these categories with these
columns:
ID (this will be the unique identifier);
Name (This is the name that will be shown to the public);
Parent (This is the id of the category that includes this category);

and would like to be able to print something like this:
Main category
- Child 1 of main
- - Child 1 of child 1
- - Child 2 of child 1
- Child 2 of main


But don't know how to properly write the code or desing the DB to do this.
I thought doing this with a for but I don't know how deep could a category
be.
I'd be grateful if you could guide me or give me some links that were
useful to accomplish this task.
Thank you all in advance.
Edit: I'll post the code I am using so you can see the problem
if ($result = $mysqli->query("SELECT * FROM categorias")) {
if($result->num_rows > 1) {
echo 'Number of categories: '.$result->num_rows.'<br><br>';
echo '=============x=============<br><br>';
for ($i = 1; $i <= $result->num_rows; $i++) {
$row = $result->fetch_assoc();
echo 'Categories that belong to '.$row['nombre'].'<br><br>';
if ($result2 = $mysqli->query("SELECT * FROM categorias WHERE
parent = ".$row['ID'])) {
//if($result2->num_rows > 0) {
echo 'Amount: '.$result2->num_rows.'<br><br>';
while ($row2 = $result2->fetch_assoc()) {
echo 'ID: '.$row2['ID'].', name:
'.$row2['nombre'].'<br><br>';
}
//}
}
echo '=============x=============<br><br>';
}
}
}
This code is printing:
Number of categories: 5
=============x=============
Categories that belong to Main
Amount: 2
ID: 2, name: News
ID: 4, name: Calendar
=============x=============
Categories that belong to News
Amount: 2
ID: 3, name: Twitter
ID: 5, name: Facebook
=============x=============
Categories that belong to Twitter
Amount: 0
=============x=============
Categories that belong to Calendar
Amount: 0
=============x=============
Categories that belong to Facebook
Amount: 0
=============x=============
And I need to be able to print the entire category tree.

No comments:

Post a Comment