以下代码两次插入单个记录。
注意:
除了下面的内容之外,脚本中没有其他代码(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条记录......再次 - 很奇怪: