【发布时间】:2015-03-03 14:10:53
【问题描述】:
我在使用 pdo prepare 语句在 mysql 中插入多行时遇到了一些问题。
插入有效,但只有一次。
我尝试将查询放在 foreach 之前,但同样的问题。
$product_id = $_POST['id'];
if (isset($_POST['product_attribute'])){
$att_id = array();
foreach ($_POST['product_attribute'] as $product_attribute) {
$att_id[] = $product_attribute['attribute_id'];
if ($product_attribute['attribute_id']) {
$stmt = $database->prepare("DELETE FROM product_attribute WHERE product_id =:product_id AND attribute_id=:attribute_id");
$stmt->bindParam(':product_id', $product_id, PDO::PARAM_INT);
$stmt->bindParam(':attribute_id', $product_attribute['attribute_id'], PDO::PARAM_INT);
$stmt->execute();
foreach ($product_attribute['product_attribute_description'] as $product_attribute_description) {
$stmt = $database->prepare("INSERT INTO product_attribute SET product_id=:product_id, product_code=:product_code, attribute_id=:attribute_id, `text`=:atext");
$stmt->bindParam(':product_id', $product_id, PDO::PARAM_INT);
$stmt->bindParam(':product_code', $_POST['codprodus'], PDO::PARAM_INT);
$stmt->bindParam(':attribute_id', $product_attribute['attribute_id'], PDO::PARAM_INT);
$stmt->bindParam(':atext', $product_attribute_description['text'], PDO::PARAM_STR);
$stmt->execute();
}
}
}
$vals = implode( ",", $att_id );
$stmt = $database->prepare("DELETE FROM product_attribute WHERE product_id =:product_id AND attribute_id NOT IN(:vals)");
$stmt->bindParam(':product_id', $product_id, PDO::PARAM_INT);
$stmt->bindParam(':vals', $vals, PDO::PARAM_STR);
$stmt->execute();
}else {
$stmt = $database->prepare("DELETE FROM product_attribute WHERE product_id =:product_id");
$stmt->bindParam(':product_id', $product_id, PDO::PARAM_INT);
$stmt->execute();
}
Print_r($_POST['product_attribute'] :
Array([103] => Array(
[attribute_id] => 103
[product_attribute_description] => Array
(
[2] => Array
(
[text] => 56
)
)
)
[102] => Array
(
[attribute_id] => 102
[product_attribute_description] => Array
(
[2] => Array
(
[text] => da
)
)
)
[104] => Array
(
[attribute_id] => 104
[product_attribute_description] => Array
(
[2] => Array
(
[text] => da
)
)
)
)
这是我的 product_attribute 表架构。
product_id int(11) NO PRI
attribute_id int(11) NO PRI
product_code int(11) NO
text text NO
【问题讨论】:
-
尝试从
$product_attribute_description['text']中删除['text'],因为您正在执行as $product_attribute_description -
如果我删除它,结果将是数组
-
使用
implode()查看此问答stackoverflow.com/q/7055257。 -
我会使用 'bindValue' 而不是 'bindParam'。我发现对于哪些“引用”实际上“绑定”到循环内的准备好的语句,“foreach”循环可能是“有趣的”。出于这个原因,除非使用“blob”类型之一,否则我总是使用“bindValue”。然后我显式地声明变量并绑定到它。
-
请使用“product_attribute”表定义更新您的问题。另外,我无法发现变量 '$product_id' 和 '$product_code' 的设置是什么?