0

我正在尝试运行以下查询,它是一个多插入。一切似乎都很好,但它抛出了这个错误:

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();
4

1 回答 1

2

您可能想在查询的值部分不带括号尝试:

$add_report_types=$this->prepare("
    INSERT INTO report_types (
        report_id,
        category
    ) VALUES " . $allPlaces);

如果我理解正确,$allPlaces应该包含一个如下所示的字符串:

(?, ?), (?, ?), (?, ?)

所以你希望你的查询看起来像:

INSERT INTO report_types (
    report_id,
    category
) VALUES (?, ?), (?, ?), (?, ?);

http://dev.mysql.com/doc/refman/5.5/en/insert.html

于 2013-01-20T21:42:15.683 回答