Forum Moderators: open
I am doing a little Christmas coding this evening - I have two tables: 'CATEGORIES' and 'CONTENT'.
Each record in CONTENT contains a parent_id which relates to an ID in CATEGORIES.
Categories:
id¦c_name ¦
Content:
name ¦parent_id
I want to query the CONTENT table for NAME and PARENT_ID. I then want to get the C_NAME for PARENT_ID from CATEGORIES.
i.e.
SELECT name, parent_id FROM content
and then
SELECT name FROM categories where id = '$parent_id'
Is there a more efficient way than creating two loops? This will be on 90% of my pages so it will need to be fast and efficient. I have heard of table joins and relational databases and such but I am not familiar - is this one of those jobs?
Thank you for your time.
P.S for a better WW forum any suggestions on the thread subject?
JAG
I have experienced this stump before in my self-teaching mysql + php venture - I find making these extra steps difficult.
I have searched for a simple tutorial using JOINS but I am having no luck and time is ticking away - could anyone post a tutorial or even write a short example for me?
Cheers.
So...by doing something like the following:
select t1.name, t2.c_name from content as t1 join categories as t2 on t1.parent_id = t2.id where t2.id = $parent_id
You should get what you want.
By saying 'as t1' and 'as t2' it just sets up an alias for the table names so you can just use t1.* and t2.* in the rest of the query.
By using the join with 'on t1.parent_id = t2.id' tells the query to only worry about the records that have the same id in both tables.
The 'where t2.id = $parent_id' further tells the query to just bring the results of the 2 tables back where the ids match your variable.
I haven't tested but it should work...I think :-)
JAG
Thanks to your example above, I think I am almost there. I have changed the DB field names slightly so they are more clear for me.
So here is what I have so far:
$join=mysql_query("SELECT t1.title, t2.title FROM content as t1 join categories as t2 on t1.parent_id = t2.category_id where t2.category_id = $parent_id");
while($row=mysql_fetch_array($join)){
I am getting a mysql_fetch_array(): supplied argument is not a valid MySQL result resource.
It must only be a small thing, could you jag or anyone else shed some light?
I'll keep at it none the less..
Happy new year!
I now need to get the parent_id for category_id - is this possible?
After doing the above join that gets an article and its parent category, I need the parent of that category both categories relate within the same table.
CATEGORIES
category_id¦title ¦parent_id
1 ¦example1¦2
2 ¦example2¦99
My goal is to have mysql echo out my url structure e.g:
www.domain.com/parent_title/parent2_title/article_title/
Is there an easier way of using these joins to do this or am I on the right track? I'm struggling alot with this.