• Skip to main content

Uly.me

cloud engineer

  • Home
  • About
  • Archives

comparison

Comparing Time

May 9, 2017

Here’s a neat little PHP script that compares a set date/time to the current time. The time() function sets the $now variable to the current Unix timestamp. The strtotime() function converts a date string to a Unix timestamp. The result is assigned to the $setdate variable. The two variables containing Unix timestamps are then compared. A simple if-then statement determines if the date is in the past or future.

date_default_timezone_set('America/Los_Angeles');
$setdate = strtotime("May 9, 2017 12:27PM");
$now = time();
if ( $setdate > $now ) : echo 'Future date'; else : echo 'Past date'; endif;

date_default_timezone_set('America/Los_Angeles'); $setdate = strtotime("May 9, 2017 12:27PM"); $now = time(); if ( $setdate > $now ) : echo 'Future date'; else : echo 'Past date'; endif;

You may have to change the default timezone if your server is in a different timezone.

Filed Under: PHP Tagged With: comparison, date, time, unix timestamp

Using Like in SQL

September 11, 2015

I was looking at my SQL statements the other day. I was doing a bunch of comparisons with a certain field that contain a pattern of words. My original SQL was quite tedious as displayed below. After much thought, I was able to pare it down to something much simpler. The newer SQL statement is much shorter and to the point. It uses the operator LIKE to search for a pattern.

OLD SQL

SELECT 
  * 
FROM 
  mytable 
WHERE 
( product="model-1" OR
  product="model-2" OR 
  product="model-3" OR
  product="model-4" OR
  product="model-5" OR
  product="model-6" ) AND
  id=105

SELECT * FROM mytable WHERE ( product="model-1" or product="model-2" or product="model-3" or product="model-4" or product="model-5" or product="model-6" ) AND id=105

NEW SQL

SELECT 
  * 
FROM 
  mytable 
WHERE 
  product LIKE "%model%" AND
  id=105

SELECT * FROM mytable WHERE product LIKE "%model%" AND id=105

The newer SQL is a vast improvement over the previous one. I was also forced to use parenthesis around the previous SQL statement to group together the OR comparisons. Without the parenthesis, my results were inaccurate because the AND had precedence over the OR. With an improved SQL, there’s no need to use parenthesis. Obviously the LIKE operator only works if there’s a pattern. I use % to make the search more liberal, otherwise it would look for an exact match.

Filed Under: PHP Tagged With: comparison, like, sql

  • Home
  • About
  • Archives

Copyright © 2023