显示来自加入的数据?

时间:2013-12-04 18:17:26

标签: php mysql sql

我有一个显示电影评论的页面,该页面由同一页面上的链接<a href="review.php?id='. $row['review'] . '"> Read Review </a>显示我还想显示电影标题。那么我是否必须使用联接来显示信息,还是有更简单的方法呢?我尝试过使用一些查询,但我最终得到了所有电影的标题。

这是查询首先在film.php上开始的地方

$query = "SELECT films.movie_title, films.rating, films.actor, reviewed.review,
      users.username
      FROM films
      LEFT JOIN reviewed ON films.movie_id=reviewed.movie_id
      LEFT JOIN users ON films.user_id=users.user_id";
$result = mysql_query($query) or die ("Could not execute mysql" . mysql_error());

$num = mysql_num_rows($result);

if ($num > 0) { // If it ran ok, display records.

echo "<p> There are curently $num records.</p>";

// Table header.
 echo '<table border="1" align="center" cellspacing="0" cellpadding="5">
<tr>
<td align="left"><b>Movie Title</b></td>
<td align="left"><b>Leading Actor</b></td>
<td align="left"><b>Rating</b></td>
<td align="left"><b>Author</b></td>
<td align="left"><b>Review</b></td>
</tr>';

// Fetch and print all the records.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    echo '<tr>
    <td align="left">' . $row['movie_title'] . '</td>
    <td align="left">' . $row['actor'] . '</td>
    <td align="left">' . $row['rating'] . '</td>
    <td align="left">' . $row['username'] . '</td>
    <td align="left"><a href="review.php?id='. $row['review'] .  '"> Read Review </a>
    </tr> ';
}
}
?>

现在在此页面上显示评论,但我想在sub_review容器中显示movie_title。

<body>

    <div id="sub_review_container">

        <?php




        ?>

    </div>

    <div id="Review_container">

    <?php

    $review = $_GET['id'];

    echo $review;

    ?>

    </div>

</body>

1 个答案:

答案 0 :(得分:1)

您缺少要在其中显示评论的查询中的评论ID。

也因为左连接。它显示所有记录。您应该使用内部联接进行评论和电影。应该是这样的:

 $query = "SELECT films.movie_title as movie_title, films.rating, films.actor, reviewed.review, users.username FROM films INNER JOIN reviewed ON films.movie_id=reviewed.movie_id INNER JOIN users ON films.user_id=users.user_id where reviewed.id = ... "

... reviewed.id将是您从页面传来的ID。