我很难将数据从mysql数据库显示到PHP生成的表。有趣的是,下面显示的查询在SQL中运行正常,但是当我尝试将其包装在PHP中时,它会显示空表而不会出现任何错误。
SELECT city.name, cinema.name, whattime, whichdate
FROM city, cinema, relationship
WHERE cinema.city = city.id
AND cinemaid = cinema.id
ORDER BY whichdate
这是PHP代码:
<?php
$usr = "admin";
$pwd = "";
$db = "dbname";
$host = "localhost";
$con = mysql_connect($host, $usr, $pwd) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());
$sql = "select city.name, cinema.name, whichdate, whattime ";
$sql .= "from city, cinema, relationship ";
$sql .= "where cinema.city = city.id ";
$sql .= "and cinemaid = cinema.id ";
$sql .= "order by whichdate";
$query = mysql_query($sql, $con) or die(mysql_error());
echo "<table id='premiere'>";
echo "<tr> <th>CITY</th> <th>CINEMA</th> <th>DATE</th> <th>TIME</th></tr>";
while($result = mysql_fetch_array( $query )) {
echo "<tr><td>";
echo $result['city.name'];
echo "</td><td>";
echo $result['cinema.name'];
echo "</td><td>";
echo $result['relationship.whichdate'];
echo "</td><td>";
echo $result['relationship.whattime'];
echo "</td></tr>";
}
echo "</table>";
?>
任何帮助都将不胜感激。
答案 0 :(得分:0)
您获取的数组不会将表名包括为数组键,只包含列名(如$result['whichname']
中所示)
使用city.name
和cinema.name
的列别名来区分它们。
$sql = "select city.name AS cityname, cinema.name AS cinemaname, whichdate, whattime ";
//--------------------^^^^^^^^^^^^^^^------------^^^^^^^^^^^^^^^
$sql .= "from city, cinema, relationship ";
$sql .= "where cinema.city = city.id ";
$sql .= "and cinemaid = cinema.id ";
$sql .= "order by whichdate";
然后,而不是:
while($result = mysql_fetch_array( $query )) {
echo "<tr><td>";
echo $result['city.name'];
echo "</td><td>";
echo $result['cinema.name'];
echo "</td><td>";
echo $result['relationship.whichdate'];
echo "</td><td>";
echo $result['relationship.whattime'];
echo "</td></tr>";
}
仅使用列名(或别名)作为数组键:
while($result = mysql_fetch_array( $query )) {
echo "<tr><td>";
echo $result['cityname'];
echo "</td><td>";
echo $result['cinemaname'];
echo "</td><td>";
echo $result['whichdate'];
echo "</td><td>";
echo $result['whattime'];
echo "</td></tr>";
}