Web Hosting Talk







View Full Version : Got results, but not what I want...using one query to help another


P-nut
06-17-2005, 01:32 PM
On the site I'm working I have a page that lists each "site" and each row has the screenshot, site title, category title, and the action to take (view, edit, delete).

Everything shows up correctly except the category title. The category names are kept in a seperate table (categories), and are referenced in the "site" table by their ID number (1,2,3 and so on).

Basically what I need to do is get the row for the "site" and then query the category table to display the name. All that is currently displaying now in the category cell is "Resource id #x", each incremented, even though the correct category id is selected in the database.

Below is my code; any help would be appreciated :)
<?
require ('interface.php');

$result = mysql_query("SELECT id,title,category,image_name FROM sites",$db);
?>
<center><b><a href=update.php>Add New Site</a></b></center><br>
<table width="100%" border="1" cellspacing="0" cellpadding="4">
<tr>
<td><b>Screenshot</b></td>
<td width="45%"><strong>Title</strong></td>
<td><b>Category</b></td>
<td><strong>Action</strong></td>
</tr>
<?
while ($result2 = mysql_fetch_array($result)) {
$myid= $result2['id'];
$mycat = $result2['category'];
$displaycat = mysql_query("SELECT title FROM categories WHERE id=$mycat") or die(mysql_error());
?>
<tr><td><img src=<? echo SITE_URL; ?>/images/screenshots/<? echo $result2['image_name'] ?> width=125></td>
<td><? echo $result2['title']; ?></td>
<td><? echo $displaycat ?></td>
<td><a href=view_sites.php>View</a>&nbsp;&nbsp;<a href=update.php?id=<? echo $myid; ?>>Edit</a>&nbsp;&nbsp;<a href=delete_sites.php?id=<? echo $myid; ?>>Delete</a></td>
</tr>
<? } ?>
</table>

maxymizer
06-17-2005, 01:50 PM
You didn't go trough while - mysql_fetch_array thingy with $displaycat.
$displaycat is a resource pointing to result of a query and you're not echoing the results, you are echoing the pointer.
Anyway, you could perform this with 1 query since it seems the tables are in 1:1 relationship.

Query:

SELECT
s.id,
s.title,
s.image_name,
c.title as category
FROM
sites s
LEFT JOIN
categories c
ON
s.category = c.id