我对自己做错了什么感到困惑。我在很多资源中都看过这个,包括我正在学习PHP的那本书,看起来它应该是正确的......但它只是不起作用。
<?php
try
{
$sql = 'SELECT parks.id, parks.state, parks.name, parks.description, parks.site, parks.sname, parks.street, parks.city, parks.zip, parks.phone FROM parks
INNER JOIN comments ON parks.parkid = comments.parkid
INNER JOIN photos ON parks.parkid = photos.parkid
INNER JOIN events ON parks.parkid = events.parkid';
$result = $pdo->query($sql);
}
catch (PDOException $e)
{
$error = 'Error fetching data: ' . $e->getMessage();
include 'output.html.php';
exit();
}
foreach ($result as $row)
{
$datas[] = array ('id' =>$row['id'],
'parkid' =>$row['parkid'],
'state' =>$row['state'],
'name' =>$row['name'],
'description' =>$row['description'],
'site' =>$row['site'],
'sname' =>$row['sname'],
'street' =>$row['street'],
'city' =>$row['city'],
'phone' =>$row['phone'],
'zip' =>$row['zip'],
'commentname' =>$row['commentname'],
'comment' =>$row['comment'],
'event' =>$row['event'],
'date' =>$row['date'],
'description2' =>$row['description2']);
}
include 'writing.html.php';
这将返回第一个表(公园)中的所有数据。条目注释名称,注释,事件,日期和描述2来自连接表(事件和注释)
如果我回应'$ row ['state']'我会得到一个正确答案。但是,如果我回显其他表中的任何项目(例如$ row ['comment']),我就没有结果。
我错过了什么?
答案 0 :(得分:0)
您没有编写查询以返回它们......
<?php
try
{
$sql = 'SELECT parks.id, parks.state, parks.name, parks.description, parks.site, parks.sname, parks.street, parks.city, parks.zip, parks.phone
--insert here any other column names you want to have in PHP
FROM parks
INNER JOIN comments ON parks.parkid = comments.parkid
INNER JOIN photos ON parks.parkid = photos.parkid
INNER JOIN events ON parks.parkid = events.parkid';
$result = $pdo->query($sql);
}
或者你可以得到所有(提防,如果tabl中有列; es具有相同的名称,这将无效!):
$sql = 'SELECT *
FROM parks
INNER JOIN comments ON parks.parkid = comments.parkid
INNER JOIN photos ON parks.parkid = photos.parkid
INNER JOIN events ON parks.parkid = events.parkid';
答案 1 :(得分:0)
请试试这个:
try
{
$sql = 'SELECT parks.id, parks.state, parks.name, parks.description, parks.site, parks.sname, parks.street, parks.city, parks.zip, parks.phone FROM parks
INNER JOIN comments INNER JOIN photos INNER JOIN events ON parks.parkid = comments.parkid and parks.parkid = photos.parkid and parks.parkid = events.parkid';
$result = $pdo->query($sql);
}
答案 2 :(得分:0)
SQL显示如何从连接表中返回列
SELECT parks.id,
parks.state,
parks.name AS park_name, -- use an alias when column names exist in more than one table
parks.description,
parks.site,
parks.sname,
parks.street,
parks.city,
parks.zip,
parks.phone,
comments.comment, -- to return the comment from the comments table
events.name AS event_name, -- return name from the event table
event_date -- return date from the event table
FROM parks
INNER JOIN comments
ON parks.parkid = comments.parkid
INNER JOIN photos
ON parks.parkid = photos.parkid
INNER JOIN events
ON parks.parkid = events.parkid'
;
这不是一个完整的解决方案,而是演示ho从连接表中返回数据而不是纯粹从主表中返回