Welcome Guest, Not a member yet? Register   Sign In
How to update all rows in database using batch update?
#3

(04-20-2015, 03:00 PM)silentium Wrote: Hi,

I would do something like this. Added comments to the code to try and make it clear how it works.

Controller

PHP Code:
function ghjk()
{
 
   $this->load->helper('text');
 
   $this->load->model("model_get");

 
   // Get title and id form database
 
   // Assuming that $results includes row ID and title
 
   $results $this->model_get->getalltitles();

 
   // Set $data array but leave it empty for now.
 
   $data = array();

 
   // Get key and value
 
   foreach ($results as $key => $value)
 
   {
 
       // Clean the slug
 
       $cleanslug convert_accented_characters($value['site_title']);

 
       // Add cleaned title and id to new data array.
 
       // By using the key value, we create a new array for each row
 
       // in the already existsing data array that we created earlier.
 
       // This also gives us the correct formatted array for update_batch()
 
       // function later.
 
       
        $data
[$key]['slug'   url_title($cleanslug,'-',TRUE);
 
       $data[$key]['site_id'] = $value['site_id'];
 
   }

 
   // Print out array for debug
 
   print_r($data);

 
   // Update database
 
   $this->model_get->updateall($data);


Model

PHP Code:
function updateall($data = array())
{
 
   // Check so incoming data is actually an array and not empty
 
   if (is_array($data) && ! empty($data))
 
   {
 
       // We already have a correctly formatted array from the controller,
 
       // so no need to do anything else here, just update.
 
       
        
// Update rows in database
 
       $this->db->update_batch('newsites'$data'site_id');
 
   }


A small note. In your original code you load the model twice in the same controller function. You only need to load it once, so I removed the second loading in my example.



Thank you very much man. It worked like a charm. It took my day but you saved me thanks.
Reply


Messages In This Thread
RE: How to update all rows in database using batch update? - by paju89 - 04-21-2015, 12:22 AM



Theme © iAndrew 2016 - Forum software by © MyBB