NamePros.Com (http://www.namepros.com/)
-   Programming (http://www.namepros.com/programming/)
-   -   [resolved] join query, how to output? (http://www.namepros.com/programming/455420-resolved-join-query-how-to-output.html)

liam_d 04-09-2008 06:26 AM

join query, how to output?
 
Hi all, i have this query i need to echo out all the contents in a loop:

Code:
SELECT n.poster_id, n.date, n.subject, n.post, m.mid, m.username FROM news n INNER JOIN members m ON n.poster_id = m.mid ORDER BY n.nid DESC LIMIT 6


Although my while loop using a mysql_fetch_array gives this error:

Quote:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/altercod/public_html/mecha00.com/index2modules/news.php on line 19



What is the correct way to loop through the data of a joined sql statement? And then echo it out?

Skeeter 04-09-2008 02:45 PM

aliases
 
I see you resolved this but just in case someone else wants to know...

When you use a join query in PHP you have to alias the column names

example:

SELECT
n.poster_id AS Poster_ID,
n.date AS Date_Whatever,
n.subject AS Subject,
n.post AS Post,

You can then reference your columns in your PHP code by using the aliases

PHP Code:
$str_PosterID=$row_Recordset1['Poster_ID'];


If you resolved the issue some other way please share. Thanks

SecondVersion 04-09-2008 06:59 PM

Originally Posted by Skeeter
I see you resolved this but just in case someone else wants to know...

When you use a join query in PHP you have to alias the column names

example:

SELECT
n.poster_id AS Poster_ID,
n.date AS Date_Whatever,
n.subject AS Subject,
n.post AS Post,

You can then reference your columns in your PHP code by using the aliases

PHP Code:
$str_PosterID=$row_Recordset1['Poster_ID'];


If you resolved the issue some other way please share. Thanks


Not necessarily. You'd only really need to alias if you're selecting/using columns from both tables, that are the same. Eg: if you need to use 'username', but you're SELECT'ing the 'username' field from both tables.

This could have been resolved with:
Code:
SELECT n.poster_id, n.date, n.subject, n.post, m.mid, m.username FROM news n, members m WHERE n.poster_id = m.mid ORDER BY n.nid DESC LIMIT 6


OR

Code:
SELECT n.poster_id, n.date, n.subject, n.post, m.mid, m.username FROM news AS n LEFT JOIN members AS m ON (n.poster_id = m.mid) ORDER BY n.nid DESC LIMIT 6

liam_d 04-10-2008 05:30 AM

Thanks for the replies and yes it is not needed to give each field a name unless they have the same name.


All times are GMT -7. The time now is 11:38 PM.
Site Sponsors
Advertise your business at NamePros

Powered by: vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 2.4.0