I am struggling to insert mySQL data into multiple tables using PHP statements.
I have two tables:
user
user_ID (PK)
first_name
last_name
password
profile
profile_ID (PK)
user_ID (FK)
profile_image
profile_image_name
I update the user table like so:
$sql = "INSERT INTO user (first_name, last_name, email, password)
VALUES
('$_POST[first_name]', '$_POST[last_name]', '$_POST[email]', '$_POST[password]')";
The user_ID is set to auto increment in the database, so when this code is executed the inserted data is automatically assigned to a unique PK, and stored in a session. At this same point though (creating the account) I need to insert the user_ID into the profile table as the FK. That way when the user uploads their profile image, it will be assigned to they will have a record in the profile table.
For example, on the image upload page I'm using this code:
$user_ID = $_SESSION['login'];
$ins1 = mysqli_query($db, "UPDATE profile SET `profile_image_name`='" . $profile_image_name . "' WHERE `user_ID`='$user_ID'");
$ins2 = mysqli_query($db, "UPDATE profile SET `profile_image`='" . $profile_image . "' WHERE `user_ID`='$user_ID'");
This code only works if the user_ID FK is already present in the profile table so how do I insert it using php statements like the one I did earlier? I tried using the first approach again but it doesn't seem to be working...
mysqliyou should be using parameterized queries andbind_paramto add user data to your query. DO NOT use string interpolation or concatenation to accomplish this because you will create severe SQL injection bugs. NEVER put$_POSTdata directly into a query.