3

I have two tables

  1. user_details
  2. load_owner

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

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. My PHP code is following

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();
     }
 }
 ?>   
reachrk
  • 103
  • 6
  • 1
    Possible duplicate of [INSERT rows into multiple tables in a single query, selecting from an involved table](http://stackoverflow.com/questions/10471757/insert-rows-into-multiple-tables-in-a-single-query-selecting-from-an-involved-t) – reachrk Nov 08 '15 at 07:14

1 Answers1

1

That is because you aren't actually specifying user_id value while inserting to load_owner table. You need to fetch the user_id value first, so that it becomes:

 $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

 $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.

Shitiz Garg
  • 604
  • 3
  • 7
  • thank you @Shitiz Garg it working. But why you use mysql_insert_id(). Can you explain me. –  Nov 12 '15 at 16:40