简体   繁体   中英

Display and order a number of results from MySQL database using PHP

I want to display and order a number of results to my webpage.

I'm still a starter with PHP but I have the following code to echo (all) data and that works pretty fine but I don't know if the code is good if I only want to show for example 5 results. And if that would work, how could I order them? (Like a top 5 for quickest time scores)

$dbhost = 'host';
$dbuser = 'user';
$dbpass = 'pass';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
    die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT name, company, time FROM tablename';

mysql_select_db('databasename');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
    die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_NUM))
{
    echo 
        "name: {$row[0]}  <br> ".
        "company: {$row[1]} <br> ".
        "time: {$row[3]} <br> "
    ;
}
mysql_free_result($retval);
mysql_close($conn);

I should somewhere add ORDER BY but can't find the right solution.

尝试这个,

$sql = 'SELECT name, company, `time` FROM tablename   ORDER BY name ASC LIMIT 5';

$sql = 'SELECT name, company, time FROM table name'; should be

$sql = 'SELECT name, company, time FROM table name ORDER BY column_name ACS | DESC';

Take a lot at the docs here .

$sql = SELECT name, company, time FROM tablename ORDERBY columnname LIMIT n;

在此,n表示要显示的记录数。

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