5

Ok here it is. i have two tables: products and product_sizes

so basically my product table has id(primary key),name(product name)and size_id(foreign key from product_sizes)

my product_sizes table has predetermined values:

size_id      name
------------------
1            1x1
2            2x2
3            3x3

and here i have a working code displaying the product tables(in html using while code):

id      name         size_id
-----------------------------
1      product 1         1
2      product 2         2
3      product 3         1

my problem is that i want to display(in html) the size name rather than its size_id, something similar to these example:

id      name         size_id
-----------------------------
1      product 1        1x1
2      product 2        2x2
3      product 3        1x1

can someone teach me how to do this?.. i need it urgently for my final project. thank you. sorry for my explanation im not good in english.

1 Answer 1

5

Use a JOIN:

SELECT p.id,
       p.name,
       ps.name AS size_name
  FROM PRODUCT p
  JOIN PRODUCT_SIZES ps ON ps.size_id = p.size_id

See this link of a visual representation of the various JOINs.

<? include ("conn.php");
   $sql = "SELECT p.id,
                  p.name,
                  ps.name AS size_name
             FROM PRODUCT p
             JOIN PRODUCT_SIZES ps ON ps.size_id = p.size_id";
   $result = mysql_query($sql, $connection) or die(mysql_error());
   while($row = mysql_fetch_array($result)) {
?>
<tr>
  <td><? echo $row['id']; ?></td>
  <td><? echo $row['name']; ?></td>
  <td><? echo $row['size_name']; ?></td> 
</tr>
<? } ?>
3
  • how would i display it in html? Commented Oct 2, 2010 at 4:58
  • already chosen your answer but i cannot see the delete link you are saying. sorry for being so dumb. its my first time here Commented Oct 2, 2010 at 5:15
  • mysql is now deprecated, you should use mysqli instead. Commented May 20, 2013 at 1:50

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.