Jump to content

PHP Mysql query issue?


pfoster77

Recommended Posts

Hi all

 

I want to display 5 records found in query and display by date order to most recent to todays date.

 

Any help most appreciated.

 

The php script below

 

<?php
include 'c/config.php';
include 'c/library/opendb.php';
include 'c/library/timeFunctions.php';
include 'c/library/displayFunctions2.php';

$query  = "SELECT * FROM events ORDER BY date,time";
$result = mysql_query($query);

while($row = mysql_fetch_assoc($result))

{
if ($row['date'] >= date('Y-m-d'))
{
displayEventsCurrent($row);
}
}

include 'c/library/closedb.php';
?>

Link to comment
https://forums.phpfreaks.com/topic/289369-php-mysql-query-issue/
Share on other sites

You could modify the query so it's sorted in descending order using DESC. More information can be found here:

http://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html

 

You could then use the LIMIT clause so the query only returns 5 results:

http://www.mysqltutorial.org/mysql-limit.aspx

 

 

Side note: in case you're not aware, the mysql_* functions have been deprecated. At some point in the near future, you'll need to switch to MySQLi or PDO. More information can be found here:

http://www.php.net/manual/en/mysqlinfo.api.choosing.php

Also, you could minimize the number of results being processed by the query with the WHERE clause. For example:

$query  = "SELECT * FROM events WHERE date >= '" . date('Y-m-d') . "' ORDER BY date DESC, time DESC LIMIT 5";

With the above query, you won't need the following if statement:

if ($row['date'] >= date('Y-m-d'))

I put in the above and removed the if statement and changed DESC on both to ASC and it works beautifully.

 

Sorry, I misread the question a bit. But I'm glad you figured it out though.  :happy-04:

 

Note that the ORDER BY clause defaults to ascending order, so the "ASC" isn't really necessary.

^^ What he said

 

 

 

Also, you could minimize the number of results being processed by the query with the WHERE clause. For example:

$query  = "SELECT * FROM events WHERE date >= '" . date('Y-m-d') . "' ORDER BY date DESC, time DESC LIMIT 5";

 

 

Use this

 

SELECT *
FROM events
WHERE date >= CURDATE()
ORDER BY date ASC, time ASC
LIMIT 5

 

Also, using * in your select is typically a bad idea unless you really need all the fields. List out only the fields you need

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.