简体   繁体   中英

How to get values greater than or equal to in Mysql database sql when its a value like 1:00 PM?

I'm trying make an sql query that uses the users current time as a variable formatted like "11:30 AM". Then, finds records greater than equal to that in the mysql db.

if(isset($_GET['curday'])){
   $curday = $_GET['curday']; // users current day value 5 for Friday
}

if(isset($_GET['time'])){
   $time = $_GET['time']; // users current time value 11:30AM

   $time = preg_replace('/[^0-9]/', '', $time);  // replacing the : and AM,PM

         $query = "SELECT id, Name, Address, Meeting_type, Latitude, Longitude, Thetime, Gender, Dayofweek, 3956 * 2 *
     ASIN(SQRT( POWER(SIN(($origLat - Latitude)*pi()/180/2),2)
     +COS($origLat*pi()/180 )*COS(Latitude*pi()/180)
     *POWER(SIN(($origLon-Longitude)*pi()/180/2),2)))
     as Distance FROM $tableName WHERE
     Longitude between ($origLon-$dist/cos(radians($origLat))*69)
     and ($origLon+$dist/cos(radians($origLat))*69)
     and Latitude between ($origLat-($dist/69))
     and ($origLat+($dist/69))
     having Distance < $dist AND Meeting_type = $id AND Dayofweek = $curday AND Thetime >= $time ORDER BY Thetime limit 100";

}

I know the AM and PM effect finding a >= value and possibly the : in the time value so I removed all but the numbers to try to help using $time = preg_replace('/[^0-9]/', '', $time); but still can't retrieve values properly. I can't use timestamp in this existing database so would prefer a solution without. It's local for now and I will put sql injection security in after I get this working.

Thanks for any input!

You can use DATE_FORMAT mysql function to format your VAR_CHAR column to date and apply your WHERE clause to it.

In your case you will have a SELECT like this:

SELECT * FROM your_table WHERE DATE_FORMAT(TheTime, "%H:%i %p") > your_value_formatted ORDER BY TheTime

Not the best way, but given what you have you could do:

REGEXP_REPLACE(Thetime, '[^0-9]', '') >= $time

But keep in mind that 12:00 PM or 1200 in this case will be greater than 1:00 PM or 100 , which is not correct. So you might want to convert to 24 hour time:

$time = date('Hi', strtotime($time));

Then:

DATE_FORMAT(TheTime, '%H%i') >= $time

So from the previous example of 12:00 PM and 1:00 PM , you will have 1200 and 1300 .

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