Search code examples
phparrayscodeigniterforeachbatch-insert

Array To String while inserting data using insert_batch in codeigniter


I am adding multiple rows in the database. I am using insert_batch in codeigniter.

I see some of the SO questions but did not get what I am doing wrong.

I have created an array using foreachloop but get this error.

This is the foreachloop:

foreach($add as $data){
    $new_add[] = array(
        'col1'=>$data['col1'],
        'col2'=>$data['col2'],
        'col3'=>$data['col3'],
        'col4'=>$data['col4'],
        'col5'=>$data['col5'],
        'col6'=>$data['col6']
    );
}

After Loop This is the array which i got after it:

Array
(
    [0] => Array
        (
            [col1] => col1_data
            [col2] => col2_data
            [col3] => col3_data
            [col4] => col4_data
            [col5] => col5_data
            [col6] => col6_data
        )

    [1] => Array
        (
            [col1] => col1_data
            [col2] => col2_data
            [col3] => col3_data
            [col4] => col4_data
            [col5] => col5_data
            [col6] => col6_data
        )

)

Insert Batch Query:

$this->db->insert_batch('test', $new_add);

Thanks To This Comment I have get what I am doing wrong. comment I done a basic error here i want to use insert_batch but somehow I forgot to add this in the query.

The Error:

A PHP Error was encountered

Severity: Notice

Message: Array to string conversion

Filename: database/DB_driver.php

Line Number: 1476

Backtrace:

File: D:\opt\wamp\www\yo_builder\application\controllers\Instalment.php Line: 85 Function: insert

File: D:\opt\wamp\www\yo_builder\index.php Line: 315 Function: require_once

This is the Second Error.

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '0, 1) VALUES (Array, Array)' at line 1

INSERT INTO test (0, 1) VALUES (Array, Array)

Filename: D:/opt/wamp/www/yo_builder/system/database/DB_driver.php

Line Number: 691


Solution

  • Try creating the array like this :

    $insertArray = array();
    foreach($add as $data){
        $new_add = array(
            'col1'=>$data['col1'],
            'col2'=>$data['col2'],
            'col3'=>$data['col3'],
            'col4'=>$data['col4'],
            'col5'=>$data['col5'],
            'col6'=>$data['col6']
        );
       array_push($insertArray,$new_add);
    }
    

    And call the insert_batch like this :

    $this->db->insert_batch('test', $insertArray); 
    

    And please verify that "col1","col2"... are valid column name of table "test".