mysql_fetch_array()TOP(10)

时间:2018-03-19 03:23:51

标签: php mysql sql

尝试在我的测试网站上做一个赞美区域

$result = mysql_query("SELECT message, username FROM compliments order by date DESC");
while($r = mysql_fetch_array($result))    
{
    $Name = $r["username"];
    $Message = $r["message"];
}
然而,

获取所有消息,

我想限制到最近的10个

所以我试过了..

$result = mysql_query("SELECT TOP(10) message, username FROM compliments order by date ASC");
while($r = mysql_fetch_array($result))    
{
    $Name = $r["username"];
    $Message = $r["message"];
}

引发错误

  

警告:mysql_fetch_array()要求参数1为资源,第52行的/var/www/vhosts/localhost/httpdocs/readcompliments.php中给出布尔值

我怎么能成功地做到这一点?

编辑:

现在使用

SELECT  message, username FROM compliments order by date ASC LIMIT 10

它有效!但问题是,它是最老的10! 我该怎么做才能获得最新的10个?

2 个答案:

答案 0 :(得分:1)

将LIMIT添加到您的查询中:

"SELECT message, username FROM compliments order by date ASC LIMIT 10;"

答案 1 :(得分:1)

不要忘记不推荐使用MySQL,将脚本更改为MySQLi

  

警告   MySQL在PHP 5.5.0中已被弃用,并在PHP 7.0.0中被删除。相反,应使用MySQLiPDO_MySQL扩展名。

$result = mysqli_query($conn, "SELECT  message, username FROM compliments order by date DESC LIMIT 10");
while($r = mysqli_fetch_array($result))    
{
    $Name = $r["username"];
    $Message = $r["message"];
}