【发布时间】:2012-01-12 16:16:42
【问题描述】:
我在尝试将数据从 MySQL 数据库显示到表时出现错误“不是唯一的表/别名”。假设它与外键有关。
这是用于创建表的 SQL,然后插入一些值。 SQL 运行良好,没有出现任何问题,但我添加了代码,因为这一切都与在屏幕上获取表格密切相关。
CREATE TABLE city (
id int not null primary key auto_increment,
name varchar(30) not null
) type=innodb;
CREATE TABLE cinema (
id int not null primary key auto_increment,
name varchar(50) not null,
city int not null,
foreign key(city) references city(id)
) type=innodb;
CREATE TABLE movie (
id int not null primary key auto_increment,
name varchar(30) not null
) type=innodb;
CREATE TABLE relationship (
whattime time NOT NULL,
whichdate date NOT NULL,
movieid int not null,
cinemaid int not null,
primary key (cinemaid, movieid),
foreign key(movieid) references movie(id),
foreign key(cinemaid) references cinema(id)
) type=innodb;
INSERT INTO city (id, name) VALUES (1, 'Paris'), (2, 'Copenhagen'), (3, 'London'), (4, 'Lisbon')
INSERT INTO movie (id, name) VALUES (1, 'The Church')
INSERT INTO cinema (id, name, city) VALUES (1, 'Pathé', 1), (2, 'Cinemaxx', 2), (3, 'Cineworld', 3), (4, 'ZON Lusomundo', 4)
INSERT INTO relationship (whattime, whichdate, movieid, cinemaid) VALUES ('21:00:00', '2011-12-27', 1, 1), ('19:30:00', '2011-12-28', 1, 2), ('20:00:00', '2011-12-27', 1, 3), ('21:00:00', '2012-01-02', 1, 4)
这是 php,它给了我 Not unique table/alias: 'cinema' 错误。任何想法为什么会这样?
<?php
include "inc/mysql_con.php";
mysql_select_db($db) or die(mysql_error());
$query = "select city.name, cinema.name, movie.name, date, time from city, cinema, relationship, movie";
$query .= "where cinema.city = city.id";
$query .= "and cinemaid = cinema.id";
$query .= "and movieid = movie.name";
$query .= "order by date";
mysql_query($query) 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['date'];
echo "</td><td>";
echo $result['time'];
echo "</td></tr>";
}
echo "</table>";
?>
更新: 现在我得到了正确的sql查询,代码如下
SELECT city.name, cinema.name, whichdate, whattime
FROM city, cinema, relationship, movie
WHERE cinema.city = city.id
AND cinemaid = cinema.id
ORDER BY whichdate
在 SQL 中可以正常显示表格,但在 PHP 中却不行:
错误:警告:mysql_fetch_array() 期望参数 1 是资源,在第 75 行的 content.php 中给出 null
第 75 行:while($query = mysql_fetch_array($result)) {
我们将不胜感激。
【问题讨论】:
-
mysql_* 函数已被弃用很长时间,并已在 PHP 7 中完全删除。您永远不应该使用 mysql_* 函数。如果您希望您的代码在当前版本的 PHP 中工作,尤其如此。请用 mysqli 或 PDO 替换它们
标签: php mysql sql html-table