我正在尝试运行以下多重插入查询。一切看起来都很好,但它抛出了这个错误:
SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 1 column(s)
我的代码如下
$report_categories=array(1,2,3);
$report_categories=array_unique($report_categories);
$rowPlaces = '(' . implode(', ', array_fill(0, 2, '?')) . ')';
$allPlaces = implode(', ', array_fill(0, count($report_categories), $rowPlaces));
$add_report_types=$this->prepare("
INSERT INTO report_types (
report_id,
category
) VALUES (
" . $allPlaces . "
)");
$i=1;
foreach($report_categories as $category_id){
$add_report_types->bindValue($i, $report_id, PDO::PARAM_INT);
$i++;
$add_report_types->bindValue($i, $category_id, PDO::PARAM_INT);
$i++;
}
$add_report_types->execute();
最佳答案
您可能想尝试在查询的值部分中不使用括号:
$add_report_types=$this->prepare("
INSERT INTO report_types (
report_id,
category
) VALUES " . $allPlaces);
如果我理解正确,$allPlaces
应该包含一个如下所示的字符串:
(?, ?), (?, ?), (?, ?)
所以你希望你的查询看起来像:
INSERT INTO report_types (
report_id,
category
) VALUES (?, ?), (?, ?), (?, ?);
关于php - 使用 PDO 的多重插入中的基数违规,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14428577/