【问题标题】:Drupal 7 db_insert array errorDrupal 7 db_insert 数组错误
【发布时间】:2016-06-24 02:19:54
【问题描述】:

我正在尝试将数组中的数据插入表中,但出现此错误:

“可捕获的致命错误:传递给 InsertQuery::values() 的参数 1 必须是一个数组,给定的布尔值”

$query = db_insert('print_aura_list_brands')
  ->fields(array(
    'brand_id',
    'brand_name',
  ));

foreach ($data as $record) {
  $query->values($record);
}
$query->execute();

Here is an image of the database table structure:

Here is an image of the array results:

【问题讨论】:

    标签: php database drupal-7


    【解决方案1】:

    查看您发布的示例链接 (drupal.org/node/310079),如果您进行一些更改,您可以使用多个值进行插入。

    在您的情况下,如果 $data 是您的第二个屏幕截图(“数组结果的图像”),您不能只迭代 $data,因为该对象中的第一个元素是布尔值(状态 -> TRUE)。

    你想迭代(数组)$data->results,除了每个结果都是一个对象,而不是它需要的数组。

    $query = db_insert('print_aura_list_brands')
      ->fields(array(
        'brand_id',
        'brand_name',
      ));
    
    foreach ($data->results as $record) {
      $query->values((array) $record);
    }
    $query->execute();
    

    【讨论】:

    • 非常感谢菲尔!这真的很有帮助。对于可能看到这篇文章的其他人,我还实现了 objToArray($data) 函数来将所有对象更改为数组。我了解到 foreach() 只能遍历一个数组。如果我说的不正确,请随时发表评论。
    【解决方案2】:

    您错误地使用了 db_insert 函数。应该是这样的:

    db_insert('example_tabel')
      ->fields(array(
        'field1' => 'value1',
        'field2' => 'value2',
        ...,
      ))
      ->execute();
    

    fields 数组应该是 'FIELDNAME' => 'VALUE',而不仅仅是字段。

    【讨论】:

    • 感谢您的快速回复!我使用了来自drupal.org/node/310079 的示例,看来我还是有点困惑。我正在尝试遍历数组的记录并将结果输入到表中。也许我的问题真的是 - 我如何引用这些值以便它们显示每条记录?
    猜你喜欢
    • 1970-01-01
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多