显示连接的sqldata

时间:2013-05-24 09:41:47

标签: php mysql

我正在尝试在单个表格框中显示来自multiple rows in sql的数据。 格式为:

"MovieTitle" "movieReleaseYear" "directorName"

The Matrix      1999             Andy Wachowski, Lana Wachowski

其中Andy Wachowski and Lana Wachowski来自不同的行,但是使用group_concat

收集

我在phpmyadmin中获取它们没有问题,但我不知道如何在php中显示它。

我有这个:

$sql="SELECT 725G54_5_movies.MovieTitle, 725G54_5_movies.movieProductionYear,      GROUP_CONCAT( 725G54_5_director.directorName ) 
                    FROM 725G54_5_movies
                    JOIN 725G54_5_directed ON 725G54_5_movies.MovieID = 725G54_5_directed.movieID
                    JOIN 725G54_5_director ON 725G54_5_directed.directorID = 725G54_5_director.directorID
                    GROUP BY 725G54_5_movies.MovieTitle
                    ORDER BY $order ASC";
                $result=mysql_query($sql);  

                //Presentation av kontakterna via while-sats till ett formulär
                while($rows=mysql_fetch_array($result)){

                echo "<tr>
                <td>"; echo $rows['MovieTitle']; echo "</td>
                <td>";  echo $rows['movieProductionYear']; echo "</td>
                <td>"; 
                    while($director=mysql_fetch_array($rows['directorName'])){ echo $director; }; 
                    echo"</td>
                </tr>";

2 个答案:

答案 0 :(得分:1)

Group Concat已经连接了导演的名称,所以你不需要在$rows['directorName']上进行迭代。这部分代码中的错误是错误的,因为$rows是查询结果中的一行, $rows['director']是此行的值,您无法迭代值。

 $sql = "SELECT GROUP_CONCAT( 725G54_5_director.directorName ) AS directorNames ..."

while($rows=mysql_fetch_array($result)){

                echo "<tr>";
                echo "<td>" . $rows['MovieTitle'] . "</td>";
                echo "<td>" . $rows['movieProductionYear'] . "</td>"
                echo "<td>" . $rows['directorNames'] . "</td>" 
                echo"</tr>";
}

您使用GROUP BY 725G54_5_movies.MovieTitle因此directorNames字段将是此电影连接的所有directorName的结果。

答案 1 :(得分:0)

关键信息是您需要为GROUP_CONCAT设置别名,以便可以在阵列中访问它。为了便于阅读,我还会在输出html块时使用Heredoc:

$sql=
"SELECT
    725G54_5_movies.MovieTitle,
    725G54_5_movies.movieProductionYear,
    GROUP_CONCAT(725G54_5_director.directorName) directorNames
FROM
    725G54_5_movies
    JOIN
    725G54_5_directed
    ON 725G54_5_movies.MovieID = 725G54_5_directed.movieID
    JOIN
    725G54_5_director
    ON 725G54_5_directed.directorID = 725G54_5_director.directorID
GROUP BY
    725G54_5_movies.MovieTitle
ORDER BY
    $order ASC";

$result=mysql_query($sql);

//Presentation av kontakterna via while-sats till ett formulär
echo "<table>";
while($rows=mysql_fetch_array($result)){
    echo <<<HTML
        <tr>
            <td>{$rows['MovieTitle']}</td>
            <td>{$rows['movieProductionYear']}</td>
            <td>{$rows['directorNames']}</td>
        </tr>
HTML;
}
echo "</table>";