user1260310
user1260310

Reputation: 2227

php/mysql/ajax join in query and accessing resulting variables

I have a query of a mysql database that joins two tables. In the first table it just pulls records based on an id. For the second table, there may or may not be matches based on a value in the first table. I want to get matches if there are any, otherwise, presumably those values of the resulting record set are empty.

The query seems to produce the right number of records. However, when I try to access values of some variables that should be present, I am not getting anything, either because I may be calling them the wrong name or they are not in recordset somehow. I am a bit fuzzy on mysql queries so would greatly appreciate any advice..

Table 1 parks

id | name | stateid 

Table 2 parksvisited

id | visited | parkid | userid

PHP script

$sql = "SELECT * 
FROM `parks` p
LEFT JOIN `parksvisited` pv
ON p.id = pv.parkid
WHERE p.stateid = '44'"

run query...

while($row = mysql_fetch_array($res))
{
if ($row['visited'] == 1) {
$visited = 1; }  
else {
$visited = 0; }
<a href="javascript:void(0);" onclick="loadParks(\''.$row['stateid'].'\',\''.$row['p.id'].'\',\''.$visited.'\');">Visited</a>

}

Basically, I get stateid but I am not getting p.id or visited. It could be I am naming them wrong or possibly they are getting left out of results somehow... Thanks for any suggestions.

Upvotes: 0

Views: 726

Answers (1)

Jason Swett
Jason Swett

Reputation: 45154

p.id is probably missing because each of p.id and pv.id are going to get returned as id, not as p.id or pv.id. Try this instead:

SELECT p.id pid,
       p.*,
       pv.id pvid,
       pv.*
FROM `parks` p
LEFT JOIN `parksvisited` pv
ON p.id = pv.parkid
WHERE p.stateid = '44'

It also doesn't look like you're selecting anything from pv in your original query, just p. See if this new query takes care of visited as well. And make sure to refer to pid as $row['pid'], not $row['p.id'].

Upvotes: 1

Related Questions