CodeIgniter Forums
Is it ok to delete like this $this->db->delete('freebook', array('day <' => $yesterday)); - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forum-23.html)
+--- Thread: Is it ok to delete like this $this->db->delete('freebook', array('day <' => $yesterday)); (/thread-61231.html)



Is it ok to delete like this $this->db->delete('freebook', array('day <' => $yesterday)); - El Forum - 10-27-2014

[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


Is it ok to delete like this $this->db->delete('freebook', array('day <' => $yesterday)); - El Forum - 10-27-2014

[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



Is it ok to delete like this $this->db->delete('freebook', array('day <' => $yesterday)); - El Forum - 10-27-2014

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


Is it ok to delete like this $this->db->delete('freebook', array('day <' => $yesterday)); - El Forum - 10-27-2014

[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();



Is it ok to delete like this $this->db->delete('freebook', array('day <' => $yesterday)); - El Forum - 10-27-2014

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