1

I am having difficulty to explain this problem, but I will try anyway.

I have two different database rows

  SOMETHING
*---------------------------------------------------------*
|    id    |    category_id    |    body                  |
*---------------------------------------------------------*

  CATEGORY
*---------------------------------------------------------*
|    id    |    title    |    description                 |
*---------------------------------------------------------*

Now, I want to extract data from both rows at the samt time, how do i do this?

I need to extract values from SOMETHING and display the info from CATEGORY from the category_id in SOMETHING - how is this done the best way ?

I use to extract values like this:

$query = mysql_query("select * from SOMETHING WHERE id='$id' LIMIT 1");

while ($row = mysql_fetch_array($query)) {
   extract($row);

}

4 Answers 4

2

Use a join

SELECT
    S.id,
    S.category_id,
    S.body,
    C.title,
    C.description
FROM SOMETHING AS S
JOIN CATEGORY AS C
ON S.category_id = C.id
WHERE id = '42'
LIMIT 1

If there might not be a matching row in the CATEGORY table you could use a LEFT JOIN instead.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, can you give me an example on how to print the description from the category then? What if both rows has "description" ?
@2by: You can give each column a unique alias. SELECT S.description AS something_description, C.description AS column_description, ...etc...
Ah okay, thanks, i will try that. And yes, i need to use LEFT JOIN i can see.
Can i select all results from SOMETHING? Like S.* ?
@2by: Yes, but there are good reasons why that is not recommended, and they have been discussed before at great length on this site so I won't repeat it all here.
0

It sounds like you should join the two tables together:

SELECT * FROM SOMETHING, CATEGORY WHERE SOMETHING.category_id=CATEGORY.id AND 
SOMETHING.id='$id' LIMIT 1

Make sure you sanitize $id coming into the database!

Comments

0
$query = mysql_query("SELECT * FROM SOMETHING INNER JOIN CATEGORY ON CATEGORY.id = SOMETHING.category_id WHERE id='$id' LIMIT 1");

This is susceptible to SQL injection though.

1 Comment

@2by - by "susceptible to SQL injection", stealthyninja is warning you against EVER passing ANY user input directly into a SQL query. GlaciesofPacis is also warning you of the same thing.
0

You definitely want a "join". Here's another example:

select a.id ID, b.title TITLE, b.description DESCRIPTION, a.body TEXT
from something a 
inner join category b on a.id = b.id;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.