Array - 将数组值插入mysql表

时间:2014-02-04 15:55:01

标签: php mysql

我有一个通过ajax调用提交数据的基本表单。数据被截取用php插入mysql数据库。问题是准备好的sql语句只提交从ajax调用发送的数组中的最后一个值。如何提交所有值?通过ajax发送的数组中的更多细节:http://3v4l.org/Jqd6U#v540

data[0][firstName]  James
data[0][lastName]   Smith
data[1][firstName]  Jane
data[1][lastName]   Doe
data[2][firstName]  Bob 
data[2][lastName]   Builder
etc..

$s = 1;
while(isset($_POST['data'][$s]['firstItem'])){
$person_fname = $_POST['data'][$s]['firstName'];
$person_lname = $_POST['data'][$s]['lastName'];

$query_init2 = "INSERT INTO person ( first_name, last_name) VALUES (:person_fname,:person_lname);";
$query_prep2 = $db_con->prepare($query_init2);
$insert_result2 = $query_prep2->execute(array(
  "person_fname" => $person_fname,
  "person_lname" => $person_lname
));
$s++;
}

2 个答案:

答案 0 :(得分:0)

尝试使用a代替每个循环而不是

data[0][firstName]  James
data[0][lastName]   Smith
data[1][firstName]  Jane
data[1][lastName]   Doe
data[2][firstName]  Bob 
data[2][lastName]   Builder
etc..

foreach($data as $d){
    $person_fname = $d['firstName'];
    $person_lname = $d['lastName'];

    $query_init2 = "INSERT INTO person ( first_name, last_name) VALUES (:person_fname,:person_lname);";
    $query_prep2 = $db_con->prepare($query_init2);
    $insert_result2 = $query_prep2->execute(array(
      "person_fname" => $person_fname,
      "person_lname" => $person_lname
    ));
}

答案 1 :(得分:0)

foreach($_POST['data'] as $key => $value){

    $f_name = $value['firstName'];
    $l_name = $value['lastName'];

    //insert here.
}