dongyuedaochen8415 2014-08-06 07:27
浏览 47
已采纳

在Codeigniter中插入Ids数组

I'm trying to insert two rows but the id of every row is in the same array, how can I insert correctly?

Because I tried by this way but only insert me the first id.

$sql = "
    INSERT INTO cars(car, price, createdDate, createdBy) 
    VALUES (".$this->db->escape($ids).",
            ".$this->db->escape($price).",
            NOW(),
            ".$this->session->userdata('admin_id').")";             

    mysql_query($sql);
    echo ($sql);

This is what I get:

INSERT INTO cars (car, price, createdDate, createdBy) 
VALUES ('217450,217449', '15', NOW(), 150) 

In car I want to insert the price, createdDate and createdBy on the two car Ids 217450,217449.

Thank you in advance.

  • 写回答

3条回答 默认 最新

  • douying7289 2014-08-06 07:37
    关注
    $ids = "217450, 217449";
    $id_explode = explode(",", $ids);
    
    foreach($id_explode as $id)
    {
        $sql = "
                 INSERT INTO cars(car, price, createdDate, createdBy) 
                 VALUES (".$this->db->escape($id).",
                 ".$this->db->escape($price).",
                 NOW(),
                 ".$this->session->userdata('admin_id').")
               ";             
    
       mysql_query($sql);
       echo ($sql);
    }
    


    But I recommend you not to use raw SQL queries as it is vulnerable to SQL injection.
    Hence, Use CI's active record:

    $ids = "217450, 217449";
    $id_explode = explode(",", $ids);
    
    $insert_batch = array();
    foreach($id_explode as $id)
    {
        $arr = array(
                  'car' => $id,
                  'price' => $price,
                  'createdDate' => NOW(),
                  'createdBy' => $this->session->userdata('admin_id'),
                 );
        $insert_batch[] = $arr;
    }
    
    $this->db->insert_batch('cars', $insert_batch); 
    


    Documentation:

    https://ellislab.com/codeigniter/user-guide/database/active_record.html

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料