我的SQL查询如下:
SET @fromyear = 1980;
SET @toyear = 1989;
SET @rank = 0;
SELECT test.Rank, test.Artist, test.Nominations
FROM(
SELECT
@rank:=@rank+1 as Rank,
noms.Artist,
noms.Nominations
FROM
(
SELECT COUNT(Name) as Nominations, Name as Artist
FROM Nominated
WHERE Year BETWEEN @fromyear AND @toyear
GROUP BY Name
ORDER BY Nominations DESC
) as noms
) as test
WHERE Rank BETWEEN 1 AND 5
它返回的内容如下:
Rank Artist Nominations
1 Michael Jackson 6
2 Lionel Richie 6
// through 5
SQL查询在phpMyAdmin上运行正常。我试图将其转换为与PHP表单一起使用。我已经接近了这一点:
<?php
$YEAR1POST=$_POST['YEAR1']; // user enters YEAR1 and YEAR2
$YEAR2POST=$_POST['YEAR2'];
$Rank = 0;
$ONE = 1;
$sql = "
SELECT test.Rank, test.Artist, test.Nominations
FROM(
SELECT
\"$Rank\" = ( \"$Rank\" + \"$ONE\" ) AS Rank,
noms.Artist,
noms.Nominations
FROM
(
SELECT COUNT(Name) as Nominations, Name as Artist
FROM Nominated
WHERE Year BETWEEN \"$YEAR1POST\" AND \"$YEAR2POST\"
GROUP BY Name
ORDER BY Nominations DESC
) as noms
) as test
WHERE Rank = 1
";
$result = mysql_query($sql, $connect);
while($row = mysql_fetch_assoc($result))
{
$rank = $row['Rank'];
$artist = $row['Artist'];
$nominations = $row['Nominations'];
echo "[Rank:] ". $rank;
echo "<br> [Artist:] ". $artist;
echo "<br> [Nominations:] ". $nominations;
echo "<br>";
echo "<br>";
}
?>
我在获取结果时没有获得任何数据。我很确定问题在于:
SELECT
\"$Rank\" = ( \"$Rank\" + \"$ONE\" ) AS Rank,
我只是不确定如何转换:
SELECT
@rank:=@rank+1 as Rank,
用于PHP表单。感谢
答案 0 :(得分:1)
SQL不是程序性的。您的SQL脚本引入了具有排名的过程元素,但PHP已经是一种过程语言。
如果只提取基本查询:
$sql =
"SELECT COUNT(Name) as Nominations, Name as Artist
FROM Nominated
WHERE Year BETWEEN '$YEAR1POST' AND '$YEAR2POST'
GROUP BY Name
ORDER BY Nominations DESC";
然后你应该返回相同的结果集,减去排名。您可以使用PHP变量以与SQL客户端脚本相同的方式生成排名。
$rank = 1;
while($row = mysql_fetch_assoc($result)) {
$artist = $row['Artist'];
$nominations = $row['Nominations'];
echo "[Rank:] ". $rank;
echo "<br> [Artist:] ". $artist;
echo "<br> [Nominations:] ". $nominations;
echo "<br>";
echo "<br>";
$rank++;
}
虽然在这个时刻敷衍了,你现在真的应该使用mysqli或PDO - 很快就会从PHP中删除mysql_ api。只要你使用绑定变量,这些在SQL注入和消除字符串转义的需要方面也更安全。