如何从table1到tabel2获取id?

时间:2014-11-20 08:32:28

标签: php mysql

if ( isset( $_POST['add'] ) ) {

      $id = $sql['id'];
      $sql = "SELECT * FROM table1 WHERE id IN (id1, id2, ..., idn)";

      $insert = "INSERT INTO table1(firstname,lastname,birthday,numbers,numbers2,aadress,vali) VALUES('$firstname','$lastname','$birthday','$number','$capture_field_vals1','$aadress','$vali')";


      $insert2 = "INSERT INTO table2(number1, number2, number3, number4, number5, number6, number7, number8, number9, number10) VALUES('" . $capture_field_vals[0] . "','" . $capture_field_vals[1] . "','" . $capture_field_vals[2] . "','" . $capture_field_vals[3] . "','" . $capture_field_vals[4] . "','" . $capture_field_vals[5] . "','" . $capture_field_vals[6] . "','" . $capture_field_vals[7] . "','" . $capture_field_vals[8] . "','" . $capture_field_vals[9] . "')";
      $insert3 = "INSERT INTO table2 (contactID) VALUES ('$id')";
                    //$sql.= " WHERE id = '$id' ";


        if(mysql_query($insert)) {
            //echo "$eesnimi $perenimi ON $aastad AASTAT VANA";
        } else {
          //echo "Cannot Insert";
          }
  if(mysql_query($insert2)) {echo "KORRAS";} else {echo "Cannot Insert";}
  if(mysql_query($insert3)){echo 'KORRAS';}  else{echo 'Cannot Insert';}
}

问题是,如何将table1 ID输入table2 contactID?

我尝试了不同的方法,但没有输出..

2 个答案:

答案 0 :(得分:1)

您可以使用此功能:mysqli_insert_id()

只需执行第一次插入并在之后请求插入ID:

$insert = "INSERT INTO table1(firstname,lastname,birthday,numbers,numbers2,aadress,vali) VALUES('$firstname','$lastname','$birthday','$number','$capture_field_vals1','$aadress','$vali')";
if(mysqli_query($insert)) {
  $insertID = mysqli_insert_id();
  $insert2 = "INSERT INTO table2(number1, number2, number3, number4, number5, number6, number7, number8, number9, number10) VALUES('" . $capture_field_vals[0] . "','" . $capture_field_vals[1] . "','" . $capture_field_vals[2] . "','" . $capture_field_vals[3] . "','" . $capture_field_vals[4] . "','" . $capture_field_vals[5] . "','" . $capture_field_vals[6] . "','" . $capture_field_vals[7] . "','" . $capture_field_vals[8] . "','" . $capture_field_vals[9] . "')";
  $insert3 = "INSERT INTO table2 (contactID) VALUES ('$insertID')";
  mysqli_query($insert2);
  mysqli_query($insert3);
}

BTW:你应该使用mysqli_ *函数而不是mysql_ *,因为它们已被弃用。

答案 1 :(得分:0)

Erki,

mysql_insert_id()返回最后一条插入记录的id,是否有任何帮助?