user3631086
user3631086

Reputation:

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

Upvotes: 0

Views: 5386

Answers (2)

Naycho334
Naycho334

Reputation: 167

The issue is you trying to insert arrays with different keys. for example:

$data = [
  [
     "key1" => "value 1",
     "key2" => "value 2",
     "key3" => "value 3",
  ],
  [
     "key1" => "value 1",
     "key2" => "value 2"
  ]
];

Upvotes: 1

Ketan Solanki
Ketan Solanki

Reputation: 697

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".

Upvotes: 0

Related Questions