Reputation: 21
I am using PHP
and SQL
and trying to insert user data into two tables upon registration. First in the user_table
and second into the character_table
. I'm using an automatically generating user_id
to link the tables and need to get the value of the user_id
from the first INSERT (into user_table)
then add it to a column in the character_table
.
I tried a few methods and here is where I ended ($username, $email, $password and $character are defined above);
$sql = "INSERT INTO
user_table (id, username, email, password)
VALUES ('NULL', '".$username."', '".$email."', '".$password."')
INSERT INTO
character_table (name, id)
VALUES ('".$character."', 'LAST_INSERT_ID()')";"
I want "id" from user_table to match with "id" inserted into character_table.
When I run the above, nothing seems to be happening. Previous attempts I always ended with id = 0. What is the correct way I can get the ID from the first INSERT?
Upvotes: 0
Views: 124
Reputation: 50034
user_table
, then grab the id
then run your insertion into your character_table
id
using mysql_insert_id
after running the insert. Note that on the php webpage detailing the mysql_insert_id
function that it is deprecated as is all mysql*
functions. Which leads to...mysql
it means you are not parameterizing your queries which means you are at a huge risk for a sql injection attack.If/when you switch over to mysqli or PDO functions you will find an equivalent mysqli_insert_id()
(or PDO::lastInsertID()
) function
Upvotes: 1