donglisi8644
2013-02-20 19:21 阅读 68

将键值对数组插入mysql数据库

Hello quick question for you guys/gals

I have a javascript object that displays as follows in the console.

Object { 10= "a@a.com", 18="b@b.com", 20="c@c.com"}

Passing this object to the backend CI Controller thru AJAX I've created the following function with CI.

function NewEMail(){
 //this is the array coming from ajax
 $test = $this -> input -> post('sendValue');
 print_r($test);

 if(is_array($test)){
  foreach($test as $t){
  //Insert the values in to the db from here.
  }
 }
}

the response from php for the print_r is as follows

Array([10] => a@a.com [18] => b@b.com [20] => c@c.com)  

I would like to push each element and value to a new row as follows.

EMAIL_TABLE

| id | cus_id | email   |  
| 1  | 10     | a@a.com |  
| 2  | 18     | b@b.com |   
| 3  | 20     | c@c.com | 

Where the 'id' is auto incremented how ever 'cus_id' and 'email' are read and stored from the array.

Any help or directions to helping me solve this would be greatly appreciated!

Thank you for reading, Regards.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    douzai6337 douzai6337 2013-02-20 19:23

    Set id as an auto_increment primary key column in your table.

    create table email (
        id int unsigned primary key auto_increment,
        cus_id int unsigned,
        email varchar(50)
    );
    
    insert into email (cus_id, email) values ('$cusid', '$email');
    

    id will then take care of itself, all you have to do is leave it alone when inserting.

    PHP code to do this in a loop:

    foreach ($test as $cusid => $email) {
        $querystring = "insert into users (cus_id, email) values ('$cusid', '$email')";
        myqsli_query($querystring);
    }
    
    点赞 评论 复制链接分享
  • douqingnao9246 douqingnao9246 2013-02-21 07:41

    You can try this:

    $test = $this->input->post('sendValue');
    
    if( is_array($test) ){
        $data = array();
        foreach ($test as $cusid => $email) {
            $data[] = array('cus_id' => $cusid, 'email' => $email);
        }
    
        $this->db->insert_batch('tablename', data);
    }
    
    点赞 评论 复制链接分享

相关推荐