如何使用PHP同时插入主键和外键值

时间:2015-11-08 07:08:33

标签: php

我有两张桌子

  1. user_details
  2. load_owner
  3. user_details

    user_id as primary key
    
    name
    
    password
    
    phone
    

    load_owner

    load_owner_id as a primary key
    
    user_id as foreign key
    
    address
    
    bank name
    

    我需要同时插入所有值。我尝试了但是在load_owner表中user_id值是插入为NULL。我的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();
         }
     }
     ?>   
    

1 个答案:

答案 0 :(得分:1)

这是因为在插入load_owner表时实际上并没有指定user_id值。您需要首先获取user_id值,以便它变为:

 $user_insert = mysql_query("insert into user_details (name, password, phone) values ('$name', '$password', '$phone')");
 $user_id = mysql_insert_id();

然后将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:使用带有预准备语句的 PDO ,此SQL查询容易出现SQL Injections,并且不推荐使用mysql库。