php - 使用 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(', ', 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 (?, ?), (?, ?), (?, ?);

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

关于php - 使用 PDO 的多重插入中的基数违规,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14428577/

相关文章:

php - 部署 Symfony2 应用程序出现 fosuserbundle 错误

php - 具有多个父 ID 的 Laravel 查询

mysql - MS Access VBA : What does OpenRecordSet return?

php - 使用 SQLite 计算大圆距离

php - 为什么即使我检查数据是否存在,我的表仍然插入重复数据? PHP-MYSQL

php - XLF (XLIFF) 文件中的 ID 在 Symfony 中重要吗?

php - HTML5 + UTF-8 : do i need to encode the GBP symbol (£)?

mysql - 带有外部 mysql 的 hive Metastore 不起作用

php - 错误: SQLSTATE[42000] When I try to update a value in a table

php - 使用具有多个 WHERE 条件的准备语句更新查询