Jump to content

Easy query?


bofett

Recommended Posts

Please help.

Table (cats)  has id, name,  parent.

I am trying to echo the name of the parent when I know the id of the child.  So for example…

id  name          parent

1  Automotive  NULL

2  Cleaning          1

3  Repair           1

 

I would like to display “ Automotive – Cleaning”  When I know id=2.  What is the best way to query for “Automotive”?

Thanks

 

Link to comment
Share on other sites

  • 2 months later...

This did the trick...

 

	function getCat($cat){
	$qr1 = mysql_query("SELECT name FROM cats WHERE id='$cat'");
	$a = mysql_fetch_object($qr1);
	return $a->name;
}
function getsubcat($cat){
	$qr1 = mysql_query("SELECT parent FROM cats WHERE id='$cat'");
	$a = mysql_fetch_object($qr1);

	if ($a->parent != "") {
	$qr2 = mysql_query("SELECT name FROM cats WHERE id=$a->parent");
	$a2 = mysql_fetch_object($qr2);
	echo "{$a2->name} - ";
 }else{
        }
  }

Link to comment
Share on other sites

Which is a very long redundant version of:

 

SELECT c1.name
FROM cats c1
INNER JOIN cats c2
     ON c1.id = c2.parent
WHERE c1.id = $id

 

right?

 

Edit: my sql should be simplified but for some reason, I can't think right now.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.