I have the following mysql table called “test”.

lets say it has the data as follows,

Now i would like to get the age of the user, for that I use the following query..
SELECT DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(DOB, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(DOB, '00-%m-%d')) AS age from test where user_name = 'akshaynhegde';
It works and returns age 21. (this is when I run the query in the terminal)
But, when I use the the following code in Drupal 6, It returns nothing…!!
global $user;
$uname = $user->name;
$sql = "SELECT DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(DOB, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(DOB, '00-%m-%d')) AS age from test where user_name = '%s'";
$age = db_result(db_query($sql,$uname));
I tried all the possibilities such as using db_fetch_array() , db_fetch_object() and separately executed $result = db_query($sql,$uname) and then passed $result to db_result()..
But NOTHING WORKS..! Why..????
Well, FYI other simple queries work.. for example the following, it works.
$sql = "select DOB from test where user_name = '%s'";
$dob = db_result(db_query($sql,$uname));
I’ve got no experience with either Drupal or PHP, but I’m sure your problem is the
%Y,%mand%dyou have in your query string. You’ll need to escape thhose so only %s is left.According to %d modifier in db_query not wanted you escape them by writing two
%instead of just one.So you query string should look like this: