在生成缓存的静态页面时,如何基于复杂SQL查询的内容动态重新排列六个PHP代码块?
我有六个功能相同的PHP代码块(下面包含一个示例),每个代码块都显示六场比赛之一的前五名。
我将PHP代码包装到function
中,但是SQL查询失败了。这是通过将数据库连接器变量作为函数参数发送来解决的,而初始疏忽是很烦人的,因为它对我来说是愚蠢的。
这是基本的SQL查询,我设计用于生成六个游戏之一的平均分数,其他五个在功能上相同。
$my_var1 = mysqli_query($connection, "SELECT AVG(score) FROM (SELECT g1_score AS score FROM game_1) TMP");
以下是自定义函数中的代码,用于显示六个前5个得分块中的一个:
function t5_game_1($connection) {
print "<p>Game 1</p>\n";
print "<table style='margin: 0 auto;'>\n";
$count = 0;
$A = mysqli_query($connection, "
SELECT players.Pname
, game_1.g1_score
, game_1.DVN
FROM players
LEFT
JOIN game_1
ON players.PID = game_1.PID
WHERE game_1.g1_seen = 'Y'
ORDER
BY game_1.g1_score DESC
LIMIT 5
");
IF ($AA = mysqli_fetch_array($A)) {
do {
print "<tr><td class='w3-left-align'>{$AA[0]}</td><td class='w3-right-align'>{$AA[1]}</td>";
SWITCH ($AA[2]) {
CASE 1:
print "<td class='w3-theme-d5'>Advanced</td>\n";
break;
CASE 2:
print "<td class='w3-theme-d5'>Intermediate</td>\n";
break;
CASE 3:
print "<td class='w3-theme-d5'>Beginner</td>\n";
break;
DEFAULT:
print "<td class='w3-theme-d5'>Beginner</td>\n";
break;
}
$count++;
} while ($AA = mysqli_fetch_array($A));
}
IF ($count < 5) {
do {
print "<tr><td colspan='3'>[Your name could be here]</td></tr>\n";
$count++;
} while ($count < 5);
}
print "</table>\n";
}
更新:我找到了部分答案,并找到了一个有效的解决方案,请参阅下面的答案。
答案 0 :(得分:0)
在建议将新信息存储到中间步骤之后,我决定使用每小时cron-job生成的缓存页面。这使得我可以像SQL查询一样复杂,因为它只运行一小时一次。这导致将此怪物SQL查询分配给$my_var1
:SQL Fiddle Link
SELECT
game,
average
FROM
(
SELECT
'1' AS game,
AVG(g1score) AS average
FROM
(
SELECT
Game1Score AS g1score
FROM
game1
) tmp1
) tmp2
UNION ALL
(
SELECT
'2' AS game,
AVG(g2score) AS average
FROM
(
SELECT
Game2Score AS g2score
FROM
game2
) tmp3
)
UNION ALL
(
SELECT
'3' AS game,
AVG(g3score) AS average
FROM
(
SELECT
Game3Score AS g3score
FROM
game3
) tmp4
)
UNION ALL
(
SELECT
'4' AS game,
AVG(g4score) AS average
FROM
(
SELECT
Game4Score AS g4score
FROM
game4
) tmp5
)
UNION ALL
(
SELECT
'5' AS game,
AVG(g5score) AS average
FROM
(
SELECT
Game5Score AS g5score
FROM
game5
) tmp7
)
UNION ALL
(
SELECT
'6' AS game,
AVG(g6score) AS average
FROM
(
SELECT
Game6Score AS g6score
FROM
game6
) tmp8
)
UNION ALL
(
SELECT
'7' AS game,
'999' AS average
)
ORDER BY
average
DESC
返回此数据集:
这是一种格式,我可以使用简单的SWITCH / CASE按所需顺序调用包含Top5乐谱的功能:
do {
SWITCH ($my_query_result) {
CASE 1:
t5_game_1($connection);
BREAK;
CASE 2:
t5_game_2($connection);
BREAK;
CASE 3:
t5_game_3($connection);
BREAK;
CASE 4:
t5_game_4($connection);
BREAK;
CASE 5:
t5_game_5($connection);
BREAK;
CASE 6:
t5_game_6($connection);
BREAK;
}
} WHILE ($my_query_result = mysqli_fetch_array($my_var1));
(是的,缺少DEFAULT CASE或CASE 7是故意的)
事情是,出于一些非常奇怪的原因,这并没有在网上直播时返回预期的结果。我从来没有弄清楚问题是什么,只是一个补丁,让它可靠地工作。也许你已经发现了怪物查询的最后一个元素中的修复,或者可能是结果的第一行?
结果的第一行不会解析。无论什么游戏都在最顶层,它总是会下降到DEFAULT动作。因此,我添加了一个多余的异常值来始终引导结果集并且由于导致问题的原因而被破坏。其余六行(如果没有数据则返回null)将被传递到SWITCH / CASE并为联盟生成六个前5个得分。
这是我通常认为的UGLY解决方案,但它有效。虽然我希望我能弄清楚为什么结果集的第一行总是失败但剩下的行不会。