PDO PHP dual record insert
Code below inserts single record twice.
Note:
there is no other code in a script besides what you see below (except for DB_HOST, DB_NAME etc. constants).
code:
$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();
}
output: (record entered twice, instead of once)
+-------------------+------------+-----------+-------+----------+ | product_option_id | product_id | option_id | value | required | +-------------------+------------+-----------+-------+----------+ | 1 | 2 | 13 | | 1 | | 2 | 2 | 13 | | 1 | +-------------------+------------+-----------+-------+----------+
EDIT:
I changed code to output something on the screen and a counter.
$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();
}
.... and this is the output on the screen - single line - yet 2 records added .. again - weird:
链接地址: http://www.djcxy.com/p/69170.html上一篇: 403禁止复选框PDO / PHP语法发行PHPMYADMIN / WAMP
下一篇: PDO PHP双记录插入
