0

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.

3
  • 2
    i think you was looking for this SELECT name, company, time FROM tablename ORDER BY columnname LIMIT 5 Commented Feb 20, 2014 at 10:56
  • Add it with the query Commented Feb 20, 2014 at 10:56
  • 1
    mysql_* functions are deprecated ... please try to use mysqli_* or PDO Commented Feb 20, 2014 at 10:58

3 Answers 3

1

Try this,

$sql = 'SELECT name, company, `time` FROM tablename   ORDER BY name ASC LIMIT 5';
Sign up to request clarification or add additional context in comments.

1 Comment

i already tried something like this but then it didn't work, somewhere I made a mistake because this one works, thanks!
0

$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.

1 Comment

Thanks Kyle, this also works (like the answer of Krish), but I was searching for the limit too so I need to choose his answer as the right one this time, I'm sorry! Thanks for the link to the docs!
0

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

Here n refers to number of records to be shown.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.