How do I fix this undefined array key?
You are staring at a stack trace that looks like this: Warning: Undefined array key "first_name". It appears in detail2.php on line 12, followed by warnings for last_name, email, and age. Immediately after, your script crashes with a foreign key constraint error because the database receives empty strings.
This is a classic symptom of a mismatch between how data is submitted to your server and how you are accessing it in PHP. The root cause isn't a database issue or a complex logic bug; it is a fundamental misunderstanding of how $_REQUEST works versus $_POST.
The $_REQUEST Trap
In your detail2.php file, you are using $_REQUEST to capture input:
$first_name = mysqli_real_escape_string($link, $_REQUEST['first_name']);
The superglobal $_REQUEST is designed to be a union of three arrays: $_GET, $_POST, and $_COOKIE. It attempts to find a variable named first_name in any of those locations.
However, your form in details.html (note the file extension mismatch in your source text, though the code provided is HTML) submits data via the POST method:
<form action="detail2.php" method="post">
<input type="text" name="first_name" id="firstName">
<!-- ... other inputs ... -->
</form>
When a browser submits a form with method="post", the data is placed into the $_POST array. It is not placed into $_GET. Unless there is also a detail2.php endpoint being called via a URL query string (e.g., detail2.php?first_name=John), $_REQUEST['first_name'] will return an empty string if the value does not exist in $_GET or $_COOKIE.
If your form fields are left blank on submission, $_POST['first_name'] exists but contains an empty string (""). While this technically avoids the "Undefined array key" warning, it leads to the next error: inserting empty strings into your database.
Why the Database Fails
The second part of your error message is critical: Cannot add or update a child row: a foreign key constraint fails.
Your details table has an id column that references the users table. The SQL you are attempting to execute is:
INSERT INTO details (first_name, last_name, email, age) VALUES ('', '', '', '')
If your users table does not have a user record with an empty string for all those fields, or if the id generation logic relies on existing data that isn't populated, the constraint fails. More importantly, inserting NULL or empty strings into a foreign key column (if id is meant to link to a specific user) breaks referential integrity.
The Fix: Use $_POST Explicitly
The most robust solution is to stop using $_REQUEST for POST data and use $_POST directly. This makes your intent explicit and prevents accidental retrieval of GET parameters that might have the same name (though unlikely in this specific case, it's a best practice).
Here is how you should modify your PHP logic:
<?php
// Attempt MySQL server connection
$link = mysqli_connect("localhost", "root", "", "record");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Check specifically for POST data to avoid undefined index notices
if (!isset($_POST['first_name']) || !isset($_POST['last_name'])) {
die("ERROR: Form data was not submitted.");
}
$first_name = mysqli_real_escape_string($link, $_POST['first_name']);
$last_name = mysqli_real_escape_string($link, $_POST['last_name']);
$email = mysqli_real_escape_string($link, $_POST['email']);
$age = mysqli_real_escape_string($link, $_POST['age']);
// Attempt insert query execution
$sql = "INSERT INTO details (first_name, last_name, email, age)
VALUES ('$first_name', '$last_name', '$email', '$age')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
// Check if the error is specifically about foreign keys before showing generic errors
if (strpos(mysqli_error($link), 'foreign key constraint fails') !== false) {
echo "ERROR: You cannot insert a record without a valid parent user ID or mismatched data.";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
mysqli_close($link);
?>
Handling Empty Inputs Gracefully
Simply switching to $_POST fixes the warning, but you still need to handle the case where fields are empty. If a user submits the form without typing anything, $_POST['first_name'] will be an empty string.
You should validate inputs before processing them. This prevents silent failures where data is saved as empty strings, which can corrupt your dataset over time.
if (empty($first_name) || empty($last_name)) {
echo "Please fill in the First Name and Last Name fields.";
exit;
}
Summary of Changes
- Switch Superglobals: Replace
$_REQUESTwith$_POSTto align with themethod="post"attribute in your HTML form. - Validate Existence: Use
isset()checks to ensure keys exist before accessing them, preventing "Undefined array key" warnings entirely. - Validate Content: Check if the values are empty strings and reject the insert if required fields are missing.
- Inspect Database Errors: When a foreign key constraint fails, it usually means the
idyou are trying to insert into doesn't exist in the parentuserstable. Ensure yourdetails.idcolumn is defined as the primary key or that you are explicitly linking to an existing user ID rather than relying on auto-increment logic that conflicts with constraints.
By tightening how you access input data and validating both structure and content, you eliminate the warnings and ensure your database integrity remains intact.