Nerdy Bunz
Nerdy Bunz

Reputation: 7437

Calculate date difference in MySQL and PHP

Let's say we have a MYSQL database, 'employees.'

The database contains a column, "EXP," which contains a String signifying the persons START DATE... example: "2015-01-11" (formatted: yyyy-mm-dd)

I would like for database queries to return a variable "experience" which is calculated by comparing the current date to the date contained in the EXP column.

This is the most recent attempt; what I'm trying:

SELECT phone, name, (DATEDIFF('CURDATE()','EXP') AS experience, bio, photo,  FROM squad

Can you tell what I am trying to accomplish? If anyone knows the correct code to put here it would be greatly appreciated.

Please note, if I simply replace the code

(DATEDIFF('CURDATE()','EXP') AS experience

with 'EXP' , then there are no errors and everything works as expected.

Upvotes: 0

Views: 446

Answers (5)

Roldan
Roldan

Reputation: 245

Try

SELECT phone, name, DATEDIFF(CURDATE(),EXP) AS experience, bio, photo,  FROM squad

Upvotes: 0

Hytool
Hytool

Reputation: 1368

Try this query,

    SELECT 
            phone, name, 
            CONCAT( 
                    FLOOR(TIMESTAMPDIFF(MONTH,exp,CURDATE())/12),
                    ' Year(s), ', 
                    (TIMESTAMPDIFF(MONTH,exp,CURDATE())%12),
                    ' Month(s)'
                  ) AS experience,
            bio, photo  
    FROM 
            squad;

Upvotes: 0

arhey
arhey

Reputation: 311

Remove quotes around CURDATE(), it is function, so quotes not needed

SELECT phone, name, (DATEDIFF(CURDATE(), EXP) AS experience, bio, photo,  FROM squad

Upvotes: 0

KP.
KP.

Reputation: 393

From what I understood from your question and from the select statement, I think you just have a wrong syntax check the below query

SELECT phone, name, DATEDIFF(now(), exp) AS experience, bio, photo
FROM squad

Upvotes: 0

user557846
user557846

Reputation:

you have extra brackets AND 'EXP' will use the string literal not the db field

    SELECT phone, name, DATEDIFF(now(), exp) AS experience, bio, photo
FROM squad

working demo: http://sqlfiddle.com/#!9/79e87/2

Upvotes: 2

Related Questions