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

时间:2013-02-20 19:21:24

标签: php javascript jquery html codeigniter

你好快速问题你们/ gals

我有一个javascript对象,在控制台中显示如下。

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

通过AJAX将此对象传递给后端CI控制器我已使用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.
  }
 }
}

php对print_r的响应如下

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

我想将每个元素和值推送到新行,如下所示。

EMAIL_TABLE

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

'id' 自动递增的位置'cus_id''email'被读取并从数组中存储。

非常感谢帮助我解决此问题的任何帮助或指示!

感谢您的阅读, 问候。

2 个答案:

答案 0 :(得分:0)

将id设置为表格中的auto_increment主键列。

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将自行处理,您只需在插入时不管它。

PHP代码在循环中执行此操作:

foreach ($test as $cusid => $email) {
    $querystring = "insert into users (cus_id, email) values ('$cusid', '$email')";
    myqsli_query($querystring);
}

答案 1 :(得分:0)

你可以试试这个:

$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);
}
相关问题