PHP and MySQL tips
Blogs20112011-09-15
print array or scalar?
My version of print array or scalar on the screen like this:
function prints($vars) {
global $config;
if (!isset($config['debug']) || (! $config['debug']) ) return;
if(is_array($vars) || is_object($vars)) {
echo "<pre>"; print_r($vars); echo "</pre>";
}
else echo $vars."<br>n";
}
Dynamic load Class class_exists — Checks if the class has been defined
if (!class_exists("someClass", false)) {
require_once "someClass.php";
}
or:
if (class_exists('MyClass')) {
$myclass = new MyClass();
}
MySQL: Date functions
If you’re looking for an SQL query that returns the number of days, hours and minutes between date1 and now:
SELECT CONCAT(DAYOFYEAR(date1)-DAYOFYEAR(NOW()),' days ',
DATE_FORMAT(ADDTIME("2000-00-00 00:00:00",
SEC_TO_TIME(TIME_TO_SEC(date1)-TIME_TO_SEC(NOW()))),'%k hours and %i minutes'))
AS time FROM time_table;
+---------------------------------+
| time |
+---------------------------------+
| 27 days 2 hours and 52 minutes |
+---------------------------------+
The following is from http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_last-day.
(1) I’m using this query for a birthday-reminder:
SELECT `geb_Geboorte`
FROM `gebruikers`
WHERE
DAYOFYEAR( curdate()) <= dayofyear( `geb_Geboorte` )
AND
DAYOFYEAR( curdate())+15 >= dayofyear( `geb_Geboorte` );
(2) Just another example on how to figure out how many days are until some birthdate (in order to do a range query, or get the “next” birthday):
SELECT name, birthday,
IF(DAYOFYEAR(birthday) >= DAYOFYEAR(NOW()),
DAYOFYEAR(birthday) - DAYOFYEAR(NOW()),
DAYOFYEAR(birthday) - DAYOFYEAR(NOW()) +
DAYOFYEAR(CONCAT(YEAR(NOW()),'-12-31')))
AS distance
FROM birthdates;
The + DAYOFYEAR(CONCAT(YEAR(NOW()),‘-12-31’)) (which is 366 or 365, depending on whether we’re in a leap year or not) takes care of the New Year’s Eve wrap around.
(3) This is another query for the birthday remainder :
SELECT * FROM `users`
WHERE
(
DAYOFYEAR( NOW() ) > DAYOFYEAR( DATE_SUB(birthdate,INTERVAL 7 DAY) )
AND
DAYOFYEAR( NOW() ) <= DAYOFYEAR( DATE_SUB(birthdate,INTERVAL 7 DAY) )+7
)
OR
(
DAYOFYEAR( NOW() ) > DAYOFYEAR( birthdate )-7
AND
DAYOFYEAR( NOW() ) <= DAYOFYEAR( birthdate )
);