how to insert foreign key into a database table using php

Avatar
  • updated
  • Answered

I need help, I haven't used foreign key in a very long time and I cant remember how too. I can insert data into the database without the foreign key into the table, but I am unable to insert data into the database with the foreign key. I have provided my code in hope that someone is able to help me. thank you.

$error_msg = "";

if (isset($_POST['firstname'], $_POST['lastname'], $_POST['homephone'], $_POST['cellphone'], $_POST['address'], $_POST['city'], $_POST['state'], $_POST['zip']))

{

// Sanitize and validate the data passed in

$firstname = filter_input(INPUT_POST, 'firstname', FILTER_SANITIZE_STRING);

$lastname = filter_input(INPUT_POST, 'lastname', FILTER_SANITIZE_STRING);

$homephone = filter_input(INPUT_POST, 'homephone', FILTER_SANITIZE_STRING);

$cellphone = filter_input(INPUT_POST, 'cellphone', FILTER_SANITIZE_STRING);

$address = filter_input(INPUT_POST, 'address', FILTER_SANITIZE_STRING);

$city = filter_input(INPUT_POST, 'city', FILTER_SANITIZE_STRING);

$state = filter_input(INPUT_POST, 'state', FILTER_SANITIZE_STRING);

$zip = filter_input(INPUT_POST, 'zip', FILTER_SANITIZE_STRING);

}

if (empty($error_msg))

{

// Insert the members info into the database

if ($insert_stmt = $mysqli->prepare("INSERT INTO members_info (members_fk, firstname, lastname, homephone, cellphone, address, city, state, zip) VALUES (( SELECT * FROM members WHERE id = '" . $_SESSION['username'] . "' ), ?, ?, ?, ?, ?, ?, ?, ?)"))

{

$insert_stmt->bind_param('sssssssss', $last_insert_id(), $firstname, $lastname, $homephone, $cellphone, $address, $city, $state, $zip);

// Execute the prepared query.

if (! $insert_stmt->execute())

{

header('Location: ../error.php?err=Registration failure: INSERT');

exit();

}

}

header('Location: ../member_profile.php');

exit();

}

Pinned replies
Avatar
anonymous
  • Answer
  • Answered

Hello! A foreign key will reference the ID of the parent table so it should only be sent that parent table's ID when submitting the form. As long as the table's foreign key matches up with the primary key of the parent table, everything should go smootly. Be sure that your tables are configured correctly for foreign keys. If you need more information on foreign keys, this guide from MySQL tutorial looks helpful. Hope that helps!

Avatar
anonymous
  • Answer
  • Answered

Hello! A foreign key will reference the ID of the parent table so it should only be sent that parent table's ID when submitting the form. As long as the table's foreign key matches up with the primary key of the parent table, everything should go smootly. Be sure that your tables are configured correctly for foreign keys. If you need more information on foreign keys, this guide from MySQL tutorial looks helpful. Hope that helps!