doutuo1908
doutuo1908
2017-06-21 14:17

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

已采纳

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 dongmo2324 4年前

    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

    点赞 评论 复制链接分享

相关推荐