[英]how to insert primary key and foreign key values at same time using PHP
I have two tables 我有两张桌子
user_details user_details
user_id as primary key
name
password
phone
load_owner load_owner
load_owner_id as a primary key
user_id as foreign key
address
bank name
I need to insert all the values at the same time. 我需要同时插入所有值。 I tried it but in load_owner table user_id values are insert as NULL. 我尝试了但是在load_owner表中user_id值是插入为NULL。 My PHP code is following 我的PHP代码如下
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$address = $_POST['address'];
$bank_name = $_POST['bank_name'];
$user_insert = mysql_query("insert into user_details (name, password, phone) values ('$name', '$password', '$phone')");
if($user_insert==false)
{
echo "".mysql_error();
}
$load_owner_insert = mysql_query("insert into load_owner ( address, bank_name) values ('$address''$bank_name')");
if($load_owner_insert==false)
{
echo "".mysql_error();
}
}
?>
That is because you aren't actually specifying user_id value while inserting to load_owner table. 这是因为在插入load_owner表时实际上并没有指定user_id值。 You need to fetch the user_id value first, so that it becomes: 您需要首先获取user_id值,以便它变为:
$user_insert = mysql_query("insert into user_details (name, password, phone) values ('$name', '$password', '$phone')");
$user_id = mysql_insert_id();
And then insert user_id into load_owner 然后将user_id插入load_owner
$load_owner_insert = mysql_query("insert into load_owner ( user_id, address, bank_name) values ($user_id, '$address', '$bank_name')");
PS: Use PDO with prepared statement , this SQL query is prone to SQL Injections and the mysql library is deprecated. PS:将PDO与预处理语句一起使用,这个SQL查询很容易出现SQL注入,并且不推荐使用mysql库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.