0

I have a very simple query but I need to make another query inside it. I have very little knowledge of SQL and PHP so I want to ask your help.

$result = mysql_query("SELECT * FROM img");
while ($row = mysql_fetch_assoc($result))
{
   $imgName = $row['name'];
   $catID = $row['catid'];
   // Problem
   // Need to get category NAME from category ID
   $result2 = mysql_query("SELECT name FROM cat WHERE id = $catID");
   while ($row2 = mysql_fetch_assoc($result2))
   {
      $catName = $row2['name'];
   }

   echo "Image: $imgName <br />";
   echo "Category: $catName";
}
0

3 Answers 3

4

This looks to be a simple JOIN to get the category name. You can use a single query:

SELECT
  img.id AS imgId,
  img.name AS imgName,
  cat.name AS catName
FROM img JOIN cat ON img.catid = cat.id

Replace your initial query with the above, and it will eliminate the need for the inner query.

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

2 Comments

@Qmal See edit above -- Be more explicit than img.* then. Reference image id as imgId, image name as imgName, and category name as catName in $row[]
Yea I got it that's why deleted the comment :) Thanks again
0

You could do a simple subquery on this one:

$result = mysql_query("
SELECT name, catid, (SELECT name FROM cat WHERE id = img.catid) AS cat_name
FROM img
");

1 Comment

Uh, not sure about that. If there are many rows in the table that could be quite slow. Doing an inner join seems like the much better solution.
0

This should work. You'll see all the img properties of each table in each row and in addition the cat.name value.

SELECT *, cat.name as catname FROM img
INNER JOIN cat
ON cat.id = img.catid

1 Comment

You're missing selecting cat.name at your select statement.

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.