Php 使用PDO的多插入中的基数冲突
我正在尝试运行以下查询,这是一个多重插入。一切似乎都很好,但它抛出了以下错误:Php 使用PDO的多插入中的基数冲突,php,mysql,pdo,Php,Mysql,Pdo,我正在尝试运行以下查询,这是一个多重插入。一切似乎都很好,但它抛出了以下错误: 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(', ',
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 (?, ?), (?, ?), (?, ?);
你能发布你的查询吗?我的查询就在上面的代码中。我想你需要先学会编写更可读的代码。因为我认为没有人会试图纠正这个意大利面代码,因为它不可读。我已经尝试正确格式化它。但还是很难理解。看来我忽略了这一点。