Question

I'm trying to insert into several related database tables some data after clicking a submit button, my tables are:

USERS: ID (primary key), User, Name, Password

LEVELS: ID, User_ID (foreign key), Level1, Level2, Level3, Level4

where User_ID on the table levels is the same ID as the primary key for users.

I want to make this insert with php, my code is as follows:

$host="xxxxxx"; // Host name 
$username="xxxxxx"; // Mysql username 
$password="xxxxxx"; // Mysql password 
$db_name="xxxxxx"; // Database name 
$tbl_name="USERS"; // Table name 

// Connect to server and select databse.
$dbh= mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

// sent from form 
$name=$_POST["name"]; 
$user=$_POST["user"];
$password=$_POST["password"]; 
$L4=$_POST["L4"]; 
$L3=$_POST["L3"];
$L2=$_POST["L2"]; 
$L1=$_POST["L1"]; 

$sql="INSERT INTO $tbl_name (Name, User, Password) VALUES('$name','$user','$password');";
$userid = mysql_insert_id();
$tab1= mysql_query($sql, $dbh) or die ("problem query 1");

$sql2 = "INSERT INTO LEVELS (User_ID, Level1, Level2, Level3, Level4) VALUES('$userid','$L1','$L2','$L3','$L4');";
$tab2= mysql_query($sql2, $dbh) or die ("problem query 2");

either, I don't get how to relate the tables, or something here is wrong, cause only the first sql statement is being executed, and the second one prints the die 'problem query 2'.

Can anybody please help me?

Thanks!

Était-ce utile?

La solution

$userid = mysql_insert_id();

should be called after the insert query is executed and in your case you are calling it before the first query being executed.

So it should be as

$sql="INSERT INTO $tbl_name (Name, User, Password) VALUES('$name','$user','$password');";
$tab1= mysql_query($sql, $dbh) or die ("problem query 1");
$userid = mysql_insert_id();
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top