简体   繁体   中英

Select top 5 results: PHP/SQL

I'm trying to select the top 5 results, but whenever adding order by votes desc limit 5 to this code:

$req2 = mysql_query('select id, url, name, description, banner, votes 
                     from topsite 
                     order by votes desc 
                     limit '.$first_message .','.$last_message); 
while($dnn2 = mysql_fetch_array($req2))

it won't work. How can I fix it?

If you only want the TOP 5 then you only need one limiter like this

Also if you use double quotes around your query you can expand $variables automatically, which makes it a lot easier to read and debug.

Also if you want to see the errors produced by the mysql_ extension you have to look for them

$top_5_please = 5;

$req2 = mysql_query("select id, url, name, description, banner, votes 
                     from topsite 
                     order by votes desc 
                     limit $top_5_please"); 

// error check
if ( ! $req2 ) {
    echo mysql_error();
    exit;
}

while($dnn2 = mysql_fetch_array($req2))

FINAL NOTE

Please dont use the mysql_ database extensions, it is deprecated (gone for ever in PHP7) Especially if you are just learning PHP, spend your energies learning the PDO or mysqli_ database extensions, and here is some help to decide which to use

You can try the following. Also note that mysql_* functions are deprecated. Use PDO instead.

$req2 = mysql_query('select id, url, name, description, banner, votes 
                     from topsite 
                     order by votes desc 
                     limit '.$your_limit .' OFFSET '.$your_offset); 
$req2 = mysql_query('select id, url, name, description, banner, votes 
                     from topsite 
                     order by votes desc 
                     limit 5');

you can't pass string into limit you have to use integer only in limit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM