0

I have this function,

public function storeVals($vals)
{
    $vals = explode(",", $vals);

    foreach ($vals as $val)
    {
        $val = array('input'=>$val);

        $this->db->insert('input', $val);
    }
}

The function basically receives a string e.g: This,Is,An,Example

Then it turns the string into an array with "," as a delimiter.

Then it loops through the array and inserts the data into the DB.

Code Igniter, I think, already has the functionality to do this.

File: system/database/drivers/mysql/mysql_driver.php

function _insert_batch($table, $keys, $values)
{
    return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES    ".implode(', ', $values);
}

Any ideas on how I can use insert_batch() instead of looping and inserting will be highly appreciated.

Thank you.

1 Answer 1

1

In CodeIgniter, You can use batch_insert as:

public function storeVals($vals)
{
    $vals = explode(",", $vals);

    $yourArr = array();
    foreach ($vals as $val)
    {
        $yourArr[] = array('input'=>$val); // store values in array  
    }
    $this->db->insert('tableName', $yourArr);
}

You can also follow the CI example:

$data = array(
   array(
      'title' => 'My title' ,
      'name' => 'My Name' ,
      'date' => 'My date'
   ),
   array(
      'title' => 'Another title' ,
      'name' => 'Another Name' ,
      'date' => 'Another date'
   )
);

$this->db->insert_batch('mytable', $data);

// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')

Example Reference

CI 3 User Guide (Batch Insert)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.