Shaik
Shaik

Reputation: 930

PHP select Data based on latest and previous date data respect to ID from MySQL

Have a issue to Fetch data based on most resent date entry and show "Data:abc1"

And a second one is a bit tricky

fetch Most resent data: "abc2" Which is the next most previous data after the Current one for ID "12345"

Example:1

the latest date for id:12345 is 2015-6-10 00:00:00 against A repeated data is i.e : abc1

   2015-6-10 00:00:00        13245         abc1
   2015-6-08 00:00:00        13245         abc1
   2015-6-05 00:00:00        13245         abc1 
   2015-6-06 00:00:00        13245         abc1

Expected output:1

abc1

Example:2

the most previous date for id:12345 after Current data i.e: abc1 is 2015-4-10 00:00:00

   2015-4-04 00:00:00        13245         abc2
   2015-4-10 00:00:00        13245         abc2
   2015-4-10 00:00:00        14555         abc2

Expected output:2

abc2

Database:

       TimeDate                id          data
   2015-6-10 00:00:00        13245         abc1
   2015-6-08 00:00:00        13245         abc1
   2015-6-05 00:00:00        13245         abc1 
   2015-6-06 00:00:00        13245         abc1
   2015-4-04 00:00:00        13245         abc2
   2015-4-10 00:00:00        13245         abc2
   2015-4-10 00:00:00        14555         abc2

PHP:

  $mysqli=mysqli_connect('localhost','Uname','Pass','Database');
                  $id = $_POST['idajax'];
            $query ="SELECT * FROM scores WHERE  ID='$id' ";
    $result = mysqli_query($mysqli,$query)or die(mysqli_error());
    $num_row = mysqli_num_rows($result);
                while($row=mysqli_fetch_array($result))
        {

        //Show result:




        }

Upvotes: 0

Views: 461

Answers (1)

Ravinder Reddy
Ravinder Reddy

Reputation: 24002

You can use group by clause to find most recent record of a specific id and data.

Example:

SELECT MAX( timedate ) AS timedate, id, data
  FROM scores
 GROUP BY id, data

You can include a WHERE clause to filter id or data

Upvotes: 1

Related Questions