Reputation: 187
I have this query
try
{
$sql2 = 'SELECT tpf_news.park_id name
FROM tpf_news
INNER JOIN tpf_parks ON tpf_news.park_id = tpf_parks.park_id GROUP BY name ORDER BY date DESC ' ;
$result2 = $pdo->query($sql2);
}
catch (PDOException $e)
{
$error = 'Error fetching news by park: ' . $e->getMessage();
include 'error.html.php';
exit();
}
it creates a list of theme parks that have news stories. There are many news stories per park. The problem is when I try to echo out the results in a for each loop I only see the 'park_id' not the 'name'. Below is the loop
<?php foreach ($result2 as $row2): ?>
<h3>
<?php echo $row2['name'].''.$row2['park_id']; ?>
</h3>
<br>
<?php endforeach; ?>
If I change the order I can make the 'name' appear but not 'park_id'. The weird thing is the park_id is being echoed through $row2['name'], its $row2['park_id'] that seems to do nothing. What am I doing wrong?
If it helps in the 'news' table the columns of importance are 'news_id' which is the key and 'park_id'. 'park_id' is what connects the news table to the parks table, in this table is where the 'name' is pulled from. Thanks
Upvotes: 0
Views: 62
Reputation: 2109
Either you're missing a comma between the fields:
$sql2 = 'SELECT tpf_news.park_id, name
FROM tpf_news
INNER JOIN tpf_parks ON tpf_news.park_id = tpf_parks.park_id
GROUP BY name
ORDER BY date DESC ';
Or you're trying to use an alias, which I would specify like this:
$sql2 = 'SELECT tpf_news.park_id as park_name
FROM tpf_news
INNER JOIN tpf_parks ON tpf_news.park_id = tpf_parks.park_id
GROUP BY name
ORDER BY date DESC ';
Upvotes: 1
Reputation: 36
First of all your query returns only park_id with 'name' alias. You don't select any name from the table. Second, you cannot get query result the way you do. Try this:
while($row2 = $result2->fetch()){
echo $row2['name'];
}
Upvotes: 0