Forum Moderators: coopster

Message Too Old, No Replies

Looping(?) through a mysql query until a variable equals some value

         

maccas

10:34 am on Jul 11, 2005 (gmt 0)

10+ Year Member



Hi, can someone point me in the right direction for this mysql query. I have 3 rows: id, parent and keyword. I want to print out each keyword for a particular id until the parent value gets to 0. I am not sure what to use foreach, while ...

So far I have got this

$result = mysql_query("SELECT * FROM categories WHERE id = '$id'") or die(mysql_error());
while($row = mysql_fetch_array( $result ))
{
$keyword = $row['keyword'];
$parent = $row['parent'];
}

So I want to do the above again and again .. until parent equals 0

Sarah Atkinson

3:52 pm on Jul 11, 2005 (gmt 0)

10+ Year Member



how do you know what the id is? Is id unique?

Or are your entries like

ID----ParentID----Keyword
4----5------same
4----4------blue
4---3-------widgets
4----2-------sky

etc.

IF this is the case then add an ORDER BY after the WHERE. then use the
while($row=mysql_fetch_array($results)){}

Note: you will need to ORDER BY parent decending. I'm sure you can figure they way to do that.

Sarah

maccas

4:24 pm on Jul 11, 2005 (gmt 0)

10+ Year Member



Thanks Sarah, it more like this.

id parent title
1----5------sub category
2----5------sub category
3----5------sub category
4----5------sub category
5----0------main category
6----8------sub category
7----8------sub category
8----0------main category
9----7------sub sub category

So for each id I want to print out its main category, sub category, sub sub category etc etc, where parent 0 means main category. So for example I select id 9 and get sub category 7 now I have to do the same for sub cat 7 (as parent!=0) and so on until I reach 0 (main cat). I could keep doing individual querys as it wont be more than 5 deep, but I am sure there is a better way? I proberbly made it sound more confusing than it is :)