0

I'm using CodeIgniter 3. I just need to know if there is a 'where' condition added to the query builder until now.

I'm calling a 'delete' function that deleted rows from database And it's possible to add a where condition before calling that function. Something like this:

public function delete()
{
    // Here I need to know if where condition added to the db class

    $this->db
        ->where('field', 1)
        ->delete('my_table');
}

public function main()
{
    $this->db->where('field2', 2);
    $this->delete();
} 
rostamiani
  • 2,859
  • 7
  • 38
  • 74

2 Answers2

0

In controller

function delete_row()
{
   $this->load->model('model_name');

   // Pass the id or something else to the row_delete() method
   $this->model_name->row_delete($id);
}

In Model

function row_delete($id)
{
   $this->db->where('id', $id);
   $this->db->delete('table_name'); 
}

According to your example:

public function delete_method($condition,$table_name )
{

    $this->db->where($condition)
    $this->db->delete($table_name);
}

public function main()
{
   $condition = [
     'field1'=>1,
     'field2'=>2
   ];

   $table_name = 'my_table';
   $this->delete_method($condition,$table_name );
} 
Amanullah Aman
  • 633
  • 1
  • 12
  • 29
  • Thanks. I know this method. But because of my project structure I cannot do this.There may be a lot of where conditions in various situations. Can CodeIgniter make query without resetting where conditions? – rostamiani Mar 10 '19 at 07:26
  • so according to your example, you want to delete if `field2 = 2` then you want to delete `field2=2 and field1=1` both. Am i right? – Amanullah Aman Mar 10 '19 at 07:37
  • Yes. I want to delete with both conditions. And want to find out if another 'where' clause is defined before calling 'delete_method' – rostamiani Mar 10 '19 at 07:55
  • I have edited the answer and check it after **According to your example:**. You can add your condition dynamically in `$condition` array. Hope it will help you. If it helps you then don't forget to accept my answer and upVote. :) – Amanullah Aman Mar 10 '19 at 08:11
  • Thanks, but you miss understood my question. I just want to know if any where condition is defined before or not. See my own answer. That's perfect but shows a solution – rostamiani Mar 10 '19 at 08:48
  • Yes. I got it now. Thanks, brother. – Amanullah Aman Mar 10 '19 at 09:09
0

I found a solution. The only thing I need to do is getting a select query and search for 'where' clause inside it:

public function delete()
{
    // Here I need to know if where condition added to the db class

    $sql = $this->db->get_compiled_select(NULL, FALSE);
    $has_where = stripos($sql, 'where') !== FALSE;

    // $has_where is TRUE if there is a where condition defined until now

    $this->db
        ->where('field', 1)
        ->delete('my_table');
}

public function main()
{
    $this->db->where('field2', 2);
    $this->delete();
} 
rostamiani
  • 2,859
  • 7
  • 38
  • 74