doutuo1908 2017-06-21 14:17
浏览 36
已采纳

将数组值插入数据库时​​出错[重复]

This question already has an answer here:

I am inserting multiple images into database but getting such error

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '0, 1) VALUES (Array, Array)' at line 1

INSERT INTO CompleteProjectImage (0, 1) VALUES (Array, Array)

I am holding list of selected image in the controller and passed it to my model.

Here is my model coding to insert into database.

public function create($projectDetails, $projectDescriptions, $projectImages){

    $this->db->trans_begin();


    $this->db->insert(self::$tblCompleteProject, $projectDetails);
    $insert_id = $this->db->insert_id();

    foreach ($projectDescriptions as $projectDescription) {
        $insertDescription = array(
            'project_id'   => $insert_id,
            'description'  => $projectDescription,
        );
    }

    $this->db->insert(self::$tblCompleteProjectDescription, $insertDescription);

    foreach ($projectImages as $projectImage) {
        $insertImage[] = array(
            'project_id'   => $insert_id,
            'img_src'      => $projectImage['img_src'],
        );
    }

    $this->db->insert(self::$tblCompleteProjectImage, $insertImage);  // Error inserting to this database

    if ($this->db->trans_status() === FALSE)
    {
        $this->db->trans_rollback();
    }
    else
    {
        $this->db->trans_commit();
        return ($this->db->affected_rows() != 1) ? false : true;
    }

} 

print_array($insertImage); resulting :

Array
(
    [0] => Array
        (
            [project_id] => 5
            [img_src] => 594a7f9a79285.jpg
        )

    [1] => Array
        (
            [project_id] => 5
            [img_src] => 594a7f9a792851.jpg
        )

)
</div>
  • 写回答

1条回答 默认 最新

  • dongmo2324 2017-06-21 14:20
    关注

    You can not insert an array into database you should either turn it to a Json object or select indexes one by one.

    insertImage is an array but your Insert func doesn't accept an array and directly insert the parameter in the query !

    A turnaround for you:

    foreach ($projectImages as $key => $projectImage) {
            $insertImage[$key] = array(
                'project_id'   => $insert_id,
                'img_src'      => $projectImage['img_src'],
            );
    
    $this->db->insert(self::$tblCompleteProjectImage, $insertImage[$key]);
    }
    

    I am not sure this is what you want but according to the snippet this is the proper way of inserting

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!