dongqiao6730 2016-06-25 16:21
浏览 74
已采纳

如何使用foreach将多个字段放入表中

How can I use the foreach loop to get the values for each field (brand_id & brand_name) and have them inserted into the table 'pa_list_brands'?

if I use this code:

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

I get the ERROR: "Catchable fatal error: Argument 1 passed to InsertQuery::values() must be an array, string given"

So I tried this code to see what was being returned with $record:

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

And I get ARRAY RESULT:

11Array
(
    [0] => stdClass Object
        (
            [brand_id] => 1
            [brand_name] => Gildan
        )

    [1] => stdClass Object
        (
            [brand_id] => 2
            [brand_name] => American Apparel
        )

    [2] => stdClass Object
        (
            [brand_id] => 3
            [brand_name] => Rabbit Skins
        )

    [3] => stdClass Object
        (
            [brand_id] => 4
            [brand_name] => Anvil
        )
)

Thank you, Aaron

  • 写回答

2条回答 默认 最新

  • dongxing1412 2016-06-25 18:29
    关注

    You should try this below code.Below codes assign data as an array to "values" function for $query object class.

    $query = db_insert('pa_list_brands')->fields(array('brand_id','brand_name'));
    
    foreach ($data as $key=>$record) {
    
       $values[] = $record->brand_id;
       $values[] = $record->brand_name;
       $query->values($values);
       $values=null;
    }
    $query->execute();
    

    Let me know if anything.

    If link provided in my comment doesn't helps then try this below code. You need to convert your object into array for "values" function to be work.

    function objToArray($obj) {
        if(!is_array($obj) && !is_object($obj)) 
            return $obj;
        if(is_object($obj)) 
            $obj = get_object_vars($obj);
        return 
            array_map(__FUNCTION__, $obj);
    }
    $resultarr=objToArray($data);
    if(is_array($resultarr))
      $resultarr=$resultarr[0];
    
     $query = db_insert('pa_list_brands')->fields(array('brand_id', 'brand_name'));
     foreach ($resultarr as $record) {
       $query->values($record);
     }
     $query->execute();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)