简体   繁体   中英

Moving a row from one table to another (Insert value list does not match column list)

I am using Laravel PHP framework's Fluent query builder to move rows from one table to another. PDO is being used. While using the raw query DB::query() , I get the error:

Error

SQLSTATE[21S01]: Insert value list does not match column list: 
1136 Column count doesn't match value count at row 1

SQL: INSERT IGNORE into listings_archive VALUES (?, ?)

Query

// Get rows from first table
$rows = DB::table('table_1')
        ->where('id', '>', '12345')
        ->get();

// Copy rows to second table
foreach($rows as $row) {
    $listing = get_object_vars($row);
    DB::query('INSERT IGNORE into table_2 VALUES (?, ?)', $row);
}

var_dump of $row

array(39) {
    ["id"]=>
    string(7) "2511877"
    ["name"]=>
    string(2) "AB"
    ["color"]=>
    NULL
    ["type"]=>
    NULL
    ...

What is causing the error and how can it be fixed? I tried removing the elements with NULL s but still get the same error!


UPDATE

This is possibly a problem with the array being passed into DB::query() . These very simple example gave similar errors:

$row = array('id', 123);
DB::query('INSERT IGNORE into table_2 VALUES (?, ?)', $row);

and

$row = array('id' => 123);
DB::query('INSERT IGNORE into table_2 VALUES (?, ?)', $row);

Error

SQLSTATE[21S01]: Insert value list does not match column list: 
1136 Column count doesn't match value count at row 1

Well the column count doesn't match the number of values. If you don't specify which columns, it defaults to all, so you want something like

Insert IGNORE into table_2(Column1,Column2) Values (?, ?)

Column1, Column2, being the names of the two columns in table_2 you want to put the values from Table_1 into.

Had the same Error msg, but i used mysqli in php

  • basically as stated above, if tables not identical in structure, you gotta name the fields

Solved by some tinkering:

$stmt = $con->prepare("INSERT INTO table2
                              (field1, field2, ..., )
                              SELECT
                              field1, field2, ..., 
                              FROM
                              table1 WHERE field = ? ");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM