gpt4 book ai didi

php - MySQL 循环并将变量分配给 PHP 变量

转载 作者:行者123 更新时间:2023-11-29 07:53:18 25 4
gpt4 key购买 nike

我有一个 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++;

}

最佳答案

您的查询仅返回一行,您不应在循环中调用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";
}

关于php - MySQL 循环并将变量分配给 PHP 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25828470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com