PDO PHP双记录插入

下面的代码将插入单个记录两次。

注意:

除了您在下面看到的脚本外,脚本中没有其他代码(DB_HOST,DB_NAME等常量除外)。

码:


$dbh = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES 'UTF8''));

$array = array(
    '2' => '13'
);

$sql = "INSERT INTO htdopen.oc_product_option (product_id, option_id, required) 
           VALUES (:product_id, :option_id, '1')";
$stm = $dbh->prepare($sql);

foreach ((array)$array as $key => $val)
{
    $stm->bindParam(':product_id', $key, PDO::PARAM_INT);
    $stm->bindParam(':option_id', $val, PDO::PARAM_INT);
    $stm->execute();

}

输出:(记录输入两次,而不是一次)

+-------------------+------------+-----------+-------+----------+
| product_option_id | product_id | option_id | value | required |
+-------------------+------------+-----------+-------+----------+
|                 1 |          2 |        13 |       |        1 |
|                 2 |          2 |        13 |       |        1 |
+-------------------+------------+-----------+-------+----------+

编辑:

我改变了代码以在屏幕和计数器上输出内容。


$dbh = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES 'UTF8''));

$array = array(
    '2' => '13'
);

$sql = "INSERT INTO htdopen.oc_product_option (product_id, option_id, required) 
           VALUES (:product_id, :option_id, '1')";
$stm = $dbh->prepare($sql);

$c = 0;
foreach ((array)$array as $key => $val)
{
    $c++;
    echo $c . '. ' . $key .'=>'. $val . '
'; $stm->bindParam(':product_id', $key, PDO::PARAM_INT); $stm->bindParam(':option_id', $val, PDO::PARAM_INT); $stm->execute(); }

....这是屏幕上的输出 - 单行 - 还有2个记录添加..再次 - 奇怪:

链接地址: http://www.djcxy.com/p/69169.html

上一篇: PDO PHP dual record insert

下一篇: Why isn't this PDO Exception getting caught?