使用PHP PDO插入多行

时间:2015-08-21 13:20:10

标签: php mysql pdo

我正在尝试使用PHP PDO向MySQL表插入两行。以下是我的代码

$bundleParams[] = array(
     ':bundle_contract_id' => $contract_id,
     ':bundle_clin' => $clin,
     ':constituent_clin' => $constituent_clin,
     ':constituent_quantity' => $constituent_quantity,
     ':constituent_price' => $constituent_price,
     ':base_clin' => 'Y'
);
$bundleParams[] = array(
     ':bundle_contract_id' => $contract_id,
     ':bundle_clin' => $clin,
     ':constituent_clin' => 'DELL-COMPONENTS',
     ':constituent_quantity' => $constituent_quantity,
     ':constituent_price' => 0.00,
     ':base_clin' => 'N'
);
$insertSQL = "INSERT INTO product_bundle(bundle_contract_id, bundle_clin, constituent_clin, constituent_quantity, constituent_price, base_clin) VALUES (:bundle_contract_id, :bundle_clin, :constituent_clin, :constituent_quantity, :constituent_price, :base_clin)";
$stmt = $pdo->prepare($insertSQL);
$stmt->execute($bundleParams);

当我执行代码时,我收到错误

  

致命错误:未捕获的异常'PDOException'

带有消息

  

SQLSTATE [HY093]:参数号无效

这段代码出了什么问题?谁能帮我跟踪这个问题?非常感谢你的时间。

2 个答案:

答案 0 :(得分:0)

$stmt = $pdo->prepare($insertSQL);
foreach ($bundleParams as $row)
    $stmt->execute($row);
}

所有必要的解释都可以在相关答案中找到。

答案 1 :(得分:0)

$stmt->execute($array);想要一个带有PDO绑​​定的关联数组,你给出了一个这样的数组数组 - >你必须为每一个这样做(正如你的常识所说):

foreach ($bundleParams as $row)
    $stmt->execute($row);
}