-1

trying to make a compliments area of my test site

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

this however, gets all the messages,

i want to limit to only the most recent 10

so i tried this..

$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"];
}

throws an error

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /var/www/vhosts/localhost/httpdocs/readcompliments.php on line 52

how can i do this successfuly?

EDIT:

Now using

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

and it works! but the problem is, that its getting the oldest 10! how do i make it so it gets the most recent 10?

BingBang32
  • 407
  • 1
  • 4
  • 9

3 Answers3

2

IF you are using Mysql

TOP is for sqlServer,LIMIT for Mysql

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

Instead of

SELECT TOP(10) message, username FROM compliments order by date ASC

EDIT

If you want to get most recent 10,You can use order by date DESC

SELECT  message, username FROM compliments order by date DESC LIMIT 10
D-Shih
  • 42,799
  • 6
  • 22
  • 44
1

Add LIMIT to your query:

"SELECT message, username FROM compliments order by date ASC LIMIT 10;"
Karlo Kokkak
  • 3,632
  • 4
  • 17
  • 31
1

Don't forget MySQL is deprecated, change your script to MySQLi

Warning MySQL was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.

$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"];
}