title: Codeigniter database delete and insert multiple records
body: <p>I have a problem slightly different to <a href="https://stackoverflow.com/questions/25399799/delete-and-insert-multiple-records-in-database-using-codeigniter">this</a> and <a href="https://stackoverflow.com/questions/27078616/codeigniter-deleting-multiple-records-in-checkbox">this</a>. In my model class I had to separate the delete and save into two different functions as follows.</p>
  
  <pre><code>  #save advanced preferences
  function savePreference($preferences){
  
      $this-&gt;db-&gt;insert('bingo_advanced_preferences', $preferences);  
      echo $this-&gt;db-&gt;last_query();   
  
  }
  
   #delete advanced preferences
  function deletePreference($user_id,$criteria){
  return $this-&gt;db-&gt;delete('bingo_advanced_preferences', array('bingo_user_id' =&gt; $user_id,'adv_criteria' =&gt;$criteria));
  
  }
  </code></pre>
  
  <p>if I call these functions from the controller like this delete, update works. </p>
  
  <pre><code> //language preferences
  
  
              if($this-&gt;input-&gt;post('language') &amp;&amp; count($this-&gt;input-&gt;post('language')) &gt; 0):
                  $this-&gt;Bingo_advanced_preferences-&gt;deletePreference($user,'15');
                  for ($i=0; $i &lt; count($this-&gt;input-&gt;post('language')); $i++) { 
                      $language_options = array(
                      'bingo_user_id' =&gt; $user,
                      'adv_criteria' =&gt; 15, //languages
                      'adv_criteria_value' =&gt; $this-&gt;input-&gt;post('language')[$i],
                      'adv_date_created' =&gt; date('Y-m-d H:i:s')
                      );
                  $this-&gt;Bingo_advanced_preferences-&gt;savePreference($language_options);
                  }
              endif;
  </code></pre>
  
  <p>However this doesn't cater for a scenario where somebody deselects everything so the correct order should be like this. </p>
  
  <pre><code>    $this-&gt;Bingo_advanced_preferences-&gt;deletePreference($user,'15'); 
  
      if($this-&gt;input-&gt;post('language') &amp;&amp; count($this-&gt;input-&gt;post('language')) &gt; 0):
  
              for ($i=0; $i &lt; count($this-&gt;input-&gt;post('language')); $i++) { 
                  $language_options = array(
                  'bingo_user_id' =&gt; $user,
                  'adv_criteria' =&gt; 15, //languages
                  'adv_criteria_value' =&gt; $this-&gt;input-&gt;post('language')[$i],
                  'adv_date_created' =&gt; date('Y-m-d H:i:s')
                  );
              $this-&gt;Bingo_advanced_preferences-&gt;savePreference($language_options);
              }
          endif;
  </code></pre>
  
  <p>This only deletes all the records with adv_criteria=15 and never updates(do the subsequent saving). Of course I have solved my problem with an if else statement so my question is why this doesn't work? How can we make this work?</p>