user3187017
user3187017

Reputation: 21

Delete items from database with more than x days in CodeIgniter/PHP

Can anyone tell me how to delete items from a table with more than 5 days in CodeIgniter please? I searched here and on google and can't find anything that works.

EDIT:

My table in database looks like this:

| ID| Name | CreationDate |

| 1 | Test | 01-12-2014   |

| 2 | Test2| 01-11-2014   |

and so on, I hope you understand me.

Upvotes: 0

Views: 1325

Answers (2)

S. Barrah
S. Barrah

Reputation: 26

Steps:

  1. Get the current date
  2. Calculate the date 5 days ago
  3. Delete the items from the database where the CreationDate is less than (older than) 5 days

Code:

  $date = date("Y-m-d H:i:s",time());
  $date = strtotime($date);
  $min_date = strtotime("-5 day", $date);
  $this->db->where("CreationDate < '$min_date'", NULL, FALSE);

Upvotes: 1

leogent
leogent

Reputation: 56

What is the type of CreationDate? What do you mean by more than 5 days?

If you mean you want to delete items where CreationDate is older than 5 days, and CreationDate type is string (varchar), you could use this:

$this->db->query("DELETE FROM MyTable where STR_TO_DATE(CreationDate, '%d-%m-%Y') < DATE_SUB(NOW(), INTERVAL 5 DAY)";

But if CreationDate type is mysql date, then simply use:

$this->db->query("DELETE FROM MyTable where CreationDate < DATE_SUB(NOW(), INTERVAL 5 DAY)";

Upvotes: 0

Related Questions