将数组值插入数据库时​​出错

时间:2017-06-21 14:17:22

标签: php mysql arrays codeigniter

我正在将多个图像插入数据库但是出现了这样的错误

  

您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   在第1行附近'0,1)VALUES(数组,数组)

     

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

我在控制器中保存所选图像的列表并将其传递给我的模型。

这是我的模型编码插入数据库。

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);结果:

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

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

)

1 个答案:

答案 0 :(得分:1)

您无法将数组插入数据库,您应该将其转换为Json对象或逐个选择索引。

insertImage是一个数组,但是你的Insert func不接受数组并直接在查询中插入参数!

为您带来好转:

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

$this->db->insert(self::$tblCompleteProjectImage, $insertImage[$key]);
}

我不确定这是你想要的,但根据片段,这是正确的插入方式