Question

I have a database table named ticket for storing ticket details. The structure of the table is given below:

enter image description here

As you can see, the table have a field generated_on in which I am storing the date as a UNIX TIMESTAMP. It's used for storing the date on which the ticket was generated. The ticket is valid only for next 10 days.

So whenever a user tries to use the ticket, the system should check whether the current date is within 10 days of the ticket's generated_on date. How can I check this in MySQL. I know that we can do it in other ways however, I am trying now by selecting the generated_on with the following query:

$datequery=$this->db->query("select generated_on from ticket where user_id=$userid and video_id=$videoid and status=0");

and then trying to check whether today is within 10 days. But how can check this in a single MySQL query? I am using CodeIgniter framework for my project.

Can anyone help me to find the appropriate query for this?

Thanks in advance.

Était-ce utile?

La solution

You just need to add 10 days using MySQLs DATE_ADD() function, to do that you must first convert your unix timestamp to a MySQL datetime format using FROM_UNIXTIME() then compare it against the current time with NOW()

The crucial part:

DATE_ADD(FROM_UNIXTIME(generated_on), INTERVAL 10 DAY) > NOW()

The full query:

$query = "SELECT generated_on FROM ticket WHERE user_id = " . $userid . " AND video_id = " . $videoid . " AND status = 0 AND DATE_ADD(FROM_UNIXTIME(generated_on), INTERVAL 10 DAY) > NOW()";

UPDATED BASE ON COMMENTS

Based on the comments, and rounding to whole days, you can use the following:

DATE_ADD(CAST(FROM_UNIXTIME(generated_on) AS DATE), INTERVAL 10 DAY) > CURDATE()

Simply swapping NOW() for CURDATE() we use a date rather than a datetime, we also CAST the datetime we created with FROM_UNIXTIME

The full query:

$query = "SELECT generated_on FROM ticket WHERE user_id = " . $userid . " AND video_id = " . $videoid . " AND status = 0 AND DATE_ADD(CAST(FROM_UNIXTIME(generated_on) AS DATE), INTERVAL 10 DAY) > CURDATE()";

Autres conseils

You will need the DETE_ADD() function from MySQL. http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add

Your quesry will be something like this:

select generated_on from ticket where user_id=$userid and video_id=$videoid and status=0 and generated_on <= DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL 10 DAY);

Hope this helps, Denis

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top