CodeIgniter Forums

Full Version: Is it ok to delete like this $this->db->delete('freebook', array('day <' => $yesterday));
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]gojo[/eluser]
Is it ok to use delete like this
Code:
$yesterday = date("Y-m-d");
$query = $this->db->get_where('freebook', array('day <' => $yesterday));
        if ($query->num_rows() != 0) {
        // delete all entries where it has yesterdays date
  
  $this->db->delete('freebook', array('day <' => $yesterday));

  
        }
or should I get them in a foreach and delete one at a time
Thanks in advance Gary Smile

El Forum

[eluser]RobertSF[/eluser]
No, deleting rows one at a time from an SQL database is much more inefficient than deleting them all at once. What you have there seems fine, except that wouldn't your query as you have it delete all entries with dates before yesterday?

Frankly, SQL itself is hard enough that I prefer to work out the SQL, and then just do a $this->db->query('whatever I'm doing in SQL'). As far as I can tell, the CI database method query will execute any SQL statement. Smile

El Forum

[eluser]gojo[/eluser]
Yes its to delete everything before yesterday
Thanks for your reply

El Forum

[eluser]RobertSF[/eluser]
You're welcome! By the way, now that I look closer, you don't have to check first to see if there are any entries to delete. You can just do
Code:
$this->db->delete('freebook', array('day <' => date("Y-m-d")));

If you want to determine if the query deleted any rows, you can do it after the above code, like this
Code:
$deleted_count = $this->db->affected_rows();

El Forum

[eluser]gojo[/eluser]
Thanks that's handy to know