使用pdo将多行插入mysql数据库

时间:2014-06-18 11:28:38

标签: php mysql arrays pdo

我有一个格式如下的数组

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

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

)

我的pdo sql查询如下:

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

收到错误:

PHP注意:$ stmt-> execute(array_values($ v));

上的数组到字符串转换

更新

尝试了@ 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();
}

错误:参数号无效:绑定变量数与令牌数不匹配。

上述代码有什么问题?我是新手。

3 个答案:

答案 0 :(得分:0)

$stmt = $conn->prepare($sql);添加此代码后

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

答案 1 :(得分:0)

对于目前的数据结构,您的代码是可以的。

错误表明您的数组有一些不同的结构,至少该数组有一个嵌套级别

检查您的输入数据。

答案 2 :(得分:-1)

在准备好的声明之后,首先使用bind_param,然后继续进行。