如何从第一个表到第二个表插入相同的id

时间:2016-09-10 09:11:25

标签: php mysql

我又来了,但今天我只是想问一下如何将用户的当前id插入到另一个表中。我的意思是用户在第一个中已经有了一个ID。我想在第二个表中插入完全相同的Id。

<?php
include('connect.php');
$id=$_POST['P_Id'];
$date=$_POST['appdate'];
$time=$_POST['apptime'];
$lname=$_POST['lname'];
$fname=$_POST['fname'];
$contact=$_POST['contact'];
$service=$_POST['service'];
$status = "pending";
$dentist= "Dr. Adrian Romero";
$msg= "Appointment Sucessfully Inserted ";
$update= mysql_query("INSERT INTO appointments (P_Id,LasName,FirstName,contact,appdate,apptime,service,status) values ('$id','$date','$time','$dentist','$fname','$lname','$contact','$service','$status')" );
$id=mysql_insert_id();
if($update)
{
echo "<script> alert('Thank you For Requesting an appointment. please wait for the administrator s response after 24 hrs')</script>";
header('Location:Patient.php');
}
else
{
$msge= mysql_error();
$errormsg="Something went wrong, Try again!";
echo "<script type='text/javascript'>alert('$errormsg');</script>";
}

加。我真的不了解mysql_insert_id()的功能;请帮助谢谢你有美好的一天! :D

1 个答案:

答案 0 :(得分:0)

mysql和mysqli中的基本术语是mysqli_insert_id

您的插入声明完全错误。您在Insert语句中插入了随机值。尝试使用我提到的下面的代码。

<?php
include('connect.php');
$id=$_POST['P_Id'];
$date=$_POST['appdate'];
$time=$_POST['apptime'];
$lname=$_POST['lname'];
$fname=$_POST['fname'];
$contact=$_POST['contact'];
$service=$_POST['service'];
$status = "pending";
$dentist= "Dr. Adrian Romero";
$msg= "Appointment Sucessfully Inserted ";
$query ="INSERT INTO `appointments` (`P_Id`,`LasName`,`FirstName`,`contact`,`appdate`,`apptime`,`service`,`status`) VALUES ('".$id."','".$lname."','".$fname."','".$contact."','".$date."','".$time."','".$service."','".$status."')";
$update= mysql_query($query);
$id=mysql_insert_id();
if($id)
{
echo "<script> alert('Thank you For Requesting an appointment. please wait for the administrator s response after 24 hrs')</script>";
header('Location:Patient.php');
}
else
{
$msge= mysql_error();
$errormsg="Something went wrong, Try again!";
echo "<script type='text/javascript'>alert('$errormsg');</script>";
}
?>

截至目前,mysql.*已被折旧,首选使用mysqli.*

mysqli_insert_id - 返回上次查询中使用的自动生成的ID

mysqli_insert_id()函数返回查询生成的ID,该查询在具有AUTO_INCREMENT属性的列的表上。如果最后一个查询不是INSERT或UPDATE语句,或者如果修改后的表没有具有AUTO_INCREMENT属性的列,则此函数将返回零。

  

注意:   使用LAST_INSERT_ID()函数执行INSERT或UPDATE语句也将修改mysqli_insert_id()函数返回的值。

<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Glenn','Quagmire',33)");

// Print auto-generated id
echo "New record has id: " . mysqli_insert_id($con);

mysqli_close($con);
?> 

如果您想在mysqli.*中获取最后插入的ID,则必须通过$con- connection variable以便进一步使用。