我有一个MySQL查询,它在phpmyadmin中执行时会返回正确的结果,但有人知道如何使这更加简化(更简单)以及将$trackNumber
变量附加到$info['trackName']
内PHP while循环?
$data = mysql_query(" SELECT
/* Track 1 */
( SELECT
tr.trackName
FROM league l
INNER JOIN tracks tr ON tr.trackID = l.track1
WHERE l.leagueID = 1
) AS trackName1
/* Track 2 */
, ( SELECT
tr.trackName
FROM league l
INNER JOIN tracks tr ON tr.trackID = l.track2
WHERE l.leagueID = 1
) AS trackName2
/* Track 3 */
, ( SELECT
tr.trackName
FROM league l
INNER JOIN tracks tr ON tr.trackID = l.track3
WHERE l.leagueID = 1
) AS trackName3
/* Track 4 */
, ( SELECT
tr.trackName
FROM league l
INNER JOIN tracks tr ON tr.trackID = l.track4
WHERE l.leagueID = 1
) AS trackName4
/* Track 5 */
, ( SELECT
tr.trackName
FROM league l
INNER JOIN tracks tr ON tr.trackID = l.track5
WHERE l.leagueID = 1
) AS trackName5
/* Track 6 */
, ( SELECT
tr.trackName
FROM league l
INNER JOIN tracks tr ON tr.trackID = l.track6
WHERE l.leagueID = 1
) AS trackName6
/* Track 7 */
, ( SELECT
tr.trackName
FROM league l
INNER JOIN tracks tr ON tr.trackID = l.track7
WHERE l.leagueID = 1
) AS trackName7
/* Track 8 */
, ( SELECT
tr.trackName
FROM league l
INNER JOIN tracks tr ON tr.trackID = l.track8
WHERE l.leagueID = 1
) AS trackName8
/* Track 9 */
, ( SELECT
tr.trackName
FROM league l
INNER JOIN tracks tr ON tr.trackID = l.track9
WHERE l.leagueID = 1
) AS trackName9
/* Track 10 */
, ( SELECT
tr.trackName
FROM league l
INNER JOIN tracks tr ON tr.trackID = l.track10
WHERE l.leagueID = 1
) AS trackName10
FROM league
WHERE leagueID = 1 ");
$trackNumber = 1;
while($info = mysql_fetch_assoc( $data )) {
echo "<div class=\"col-lg-3\" align=\"center\">\n";
echo " <h5> <hr/>Track " . $trackNumber . "<hr/></h5><p>" . $info['trackName['$trackNumber']'] . "</p>\n";
echo " </div>\n";
$trackNumber++;
}
答案 0 :(得分:2)
您的查询只返回一行,您不应该在循环中调用mysql_fetch_assoc()
。要访问特定轨道号的列,您需要使用字符串连接来生成数组键:$info['trackName' . $trackNumber]
$info = mysql_fetch_assoc($data);
for ($trackNumber = 1; $trackNumber <= 10; $tracknumber++) {
echo "<div class=\"col-lg-3\" align=\"center\">\n";
echo " <h5> <hr/>Track " . $trackNumber . "<hr/></h5><p>" . $info['trackName' . $trackNumber] . "</p>\n";
echo " </div>\n";
}
答案 1 :(得分:0)
您应该能够直接从每个子查询中的[曲目]中进行选择 - 对[联盟]的引用似乎是不必要的,因为您已经在查询的正文中得到了这些内容。
因此,您的第一个子查询将成为:
( SELECT
tr.trackName
FROM tracks tr
WHERE tr.trackID = l.track1
) AS trackName1
答案 2 :(得分:0)
PHP PDO:
$conn = new PDO("connectionString", $yourUsername, $yourPassword);
$std = $conn->prepare(' SELECT...(your query)');
$std->execute();
$tracks = $std->fetchAll(PDO::FETCH_OBJ);
var_dump($tracks);
foreach($tracks as $track)
{
?>
<div class=\"col-lg-3\" align=\"center\">
<h5>Number: <?= $track->trackNumber ?></h5>
<p>Name: <?= $track->trackName ?></p>
</div>
<?php
}
使用const FETCH_OBJ将返回每一行作为表列名称的表示作为属性。你可以使用FETCH_ASSOC但是会返回一个关联数组。对我来说,这将是更清晰,更优雅的方法,而不是mysql函数。