简体   繁体   中英

insert multiple rows into mysql db using pdo

I have an array in the following format

Array
(
[0] => Array
    (
        [name] => Product 1
        [weight] => 0.3000
        [Price] => 31.4400
    )

[1] => Array
    (
        [name] => Product 2
        [weight] => 0.2000
        [Price] => 32.4400
    )

)

My pdo sql query is as follows:

$sql = "INSERT INTO products(name,weight,price) VALUES (?,?,?)"; 
$stmt = $conn->prepare($sql); 
foreach ($new_items as $v) {    
    $stmt->execute(array_values($v)); 
}

Receive error:

PHP Notice: Array to string conversion on $stmt->execute(array_values($v));

Update:

Tried this code too provided by @user1978142

// insert to database
foreach($new_items as $key => $value) {
    $stmt = $conn->prepare("INSERT INTO products (name, weight, price) VALUES (:name, :weight, :price)");
    $stmt->bindParam(':name', $value['name']);
    $stmt->bindParam(':weight', $value['weight']);
    $stmt->bindParam(':price', $value['Price']);
    $stmt->execute();
}

Error: Invalid parameter number: number of bound variables does not match number of tokens.

What is wrong with both the above code ?? I am a newbie.

after $stmt = $conn->prepare($sql); add this code:

 $stmt -> bind_param("ssd", $name, $weight,$price);

For the present data structure your code is all right.

The error indicates that your array has some different structure, at least that array has one more nested level

check your input data.

准备台词之后,请先使用bind_param ,然后再继续进行。

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