I'm creating a CRUD application. When I've inserted data into the fields, I'm getting the following error:

Notice: Undefined index: firstname in C:\xampp\htdocs\crud\create.php on line 14
Notice: Undefined index: lastname in C:\xampp\htdocs\crud\create.php on line 23
Notice: Undefined index: dob in C:\xampp\htdocs\crud\create.php on line 33
Notice: Undefined index: AdmissionDate in C:\xampp\htdocs\crud\create.php on line 57
Notice: Undefined index: LastSchool in C:\xampp\htdocs\crud\create.php on line 65

Here's the code: [Added [code]...[/code] tags ~ MOD)

<?php
// Include connection file
require_once "connect.php";
 
// Define variables and initialize with empty values
$firstname = $lastname = $dob = $contact = $address = $AdmissionDate = $ReAdmissionDate = $LastSchool = $DateLeaved = $gender = "";

$firstname_err = $lastname_err = $dob_err = $contact_err = $address_err = $AdmissionDate_err = $ReAdmissionDate_err =
$LastSchool_err = $DateLeaved_err = $gender_err = "";
 
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
    // Validate name
    $input_name = trim($_POST["firstname"]);
    if(empty($input_name)){
        $firstname_err = "Please enter a name.";
    } elseif(!filter_var($input_name, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
        $firstname_err = "Please enter a valid name.";
    } else{
        $firstname = $input_name;
    }
	
$input_name = trim($_POST["lastname"]);
if(empty($input_name)){
    $lastname_err = "Please enter a name.";
} elseif(!filter_var($input_name, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
    $lastname_err = "Please enter a valid name.";
} else{
    $lastname = $input_name;
}

// validate dob
$input_dob = trim($_POST["dob"]);
if(empty($input_dob)){
    $dob_err = "Please enter birth date.";     
} else{
    $dob = $input_dob;
}

$input_contact = trim($_POST["contact"]);
if(empty($input_contact)){
    $contact_err = "Please enter contact.";     
} else{
    $contact = $input_contact;
}


// Validate address
$input_address = trim($_POST["address"]);
if(empty($input_address)){
    $address_err = "Please enter an address.";     
} else{
    $address = $input_address;
}

// Validate Admission date
$input_admission = trim($_POST["AdmissionDate"]);
if(empty($input_admission)){
    $AdmissionDate_err = "Please enter admission date.";     
} else{
    $AdmissionDate = $input_admission;
}
    
// Validate school
$input_school = trim($_POST["LastSchool"]);
if(empty($input_school)){
    $LastSchool_err = "Please enter last school attended.";     
} else{
    $LastSchool = $input_school;
}

// Validate gender
$input_gender = trim($_POST["gender"]);
if(empty($input_gender)){
    $gender_err = "Please enter gender.";     
} else{
    $gender = $input_gender;
}

// Check input errors before inserting in database
if(empty($firstname_err) && empty($lastname_err) && empty($dob_err) && empty($contact_err) && empty($address_err) 
	&& empty($AdmissionDate_err) && empty($LastSchool_err) && empty($gender_err)){
    // Prepare an insert statement
    $sql = "INSERT INTO students_records (firstname, lastname, dob, contact, address, AdmissionDate, ReAdmissionDate, LastSchool,
	DateLeaved, gender) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
     
    if($stmt = mysqli_prepare($link, $sql)){
        // Bind variables to the prepared statement as parameters
        mysqli_stmt_bind_param($stmt, "ssssssssss", $param_firstname, $param_lastname, $param_dob, $param_contact, $param_address, $param_AdmissionDate,
		$param_ReAdmissionDate, $param_LastSchool, $param_DateLeaved, $param_gender);
        
        // Set parameters
		$param_firstname = $firstname;
		$param_lastname = $lastname;
		$param_dob = $dob;
		$param_contact = $contact;
		$param_address = $address;
		$param_AdmissionDate = $AdmissionDate;
		$param_ReAdmissionDate =  $ReAdmissionDate;
		$param_LastSchool = $LastSchool;
		$param_DateLeaved = $DateLeaved;
		$param_gender = $gender;
		            
        // Attempt to execute the prepared statement
        if(mysqli_stmt_execute($stmt)){
            // Records created successfully. Redirect to landing page
            header("location: index.php");
            exit();
        } else{
            echo "Something went wrong. Please try again later.";
        }
    }
     
    // Close statement
    mysqli_stmt_close($stmt);
}

// Close connection
mysqli_close($link);
}
?>
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Create Record</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
    <style type="text/css">
        .wrapper{
            width: 500px;
            margin: 0 auto;
			margin-top: 0px;
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-12">
                    <div class="page-header">
                        <h2>Create Record</h2>
                    </div>
                    <p>Please fill this form and submit to add student record to the database.</p>
                    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                        <div class="form-group <?php echo (!empty($firstname_err)) ? 'has-error' : ''; ?>">
                            <label>First Name</label>
                            <input type="text" name="name" class="form-control" value="<?php echo $firstname; ?>">
                            <span class="help-block"><?php echo $firstname_err;?></span>
                        </div>
						<div class="form-group <?php echo (!empty($lastname_err)) ? 'has-error' : ''; ?>">
                            <label>Last Name</label>
                            <input type="text" name="name" class="form-control" value="<?php echo $lastname; ?>">
                            <span class="help-block"><?php echo $lastname_err;?></span>
                        </div>
						<div class="form-group <?php echo (!empty($dob_err)) ? 'has-error' : ''; ?>">
                            <label>Date of Birth</label>
                            <input type="date" name="name" class="form-control" value="<?php echo $dob; ?>">
                            <span class="help-block"><?php echo $dob_err;?></span>
                        </div>
						<div class="form-group <?php echo (!empty($contact_err)) ? 'has-error' : ''; ?>">
                            <label>Contact</label>
                            <input type="text" name="contact" class="form-control" value="<?php echo $contact; ?>">
                            <span class="help-block"><?php echo $contact_err;?></span>
                        </div>
                        <div class="form-group <?php echo (!empty($address_err)) ? 'has-error' : ''; ?>">
                            <label>Address</label>
                            <textarea name="address" class="form-control"><?php echo $address; ?></textarea>
                            <span class="help-block"><?php echo $address_err;?></span>
                        </div>
                        <div class="form-group <?php echo (!empty($AdmissionDate_err)) ? 'has-error' : ''; ?>">
                            <label>Date of Admission</label>
                            <input type="date" name="admission" class="form-control" value="<?php echo $AdmissionDate; ?>">
                            <span class="help-block"><?php echo $AdmissionDate_err;?></span>
                        </div>
						<div class="form-group <?php echo (!empty($ReAdmissionDate_err)) ? 'has-error' : ''; ?>">
                            <label>Date of Re-Admission</label>
                            <input type="date" name="admission" class="form-control" value="<?php echo $ReAdmissionDate; ?>">
                            <span class="help-block"><?php echo $ReAdmissionDate_err;?></span>
                        </div>
						<div class="form-group <?php echo (!empty($LastSchool_err)) ? 'has-error' : ''; ?>">
                            <label>Last School</label>
                            <input type="text" name="school" class="form-control" value="<?php echo $LastSchool; ?>">
                            <span class="help-block"><?php echo $LastSchool_err;?></span>
                        </div>
						<div class="form-group <?php echo (!empty($DateLeaved_err)) ? 'has-error' : ''; ?>">
                            <label>Date Leaved</label>
                            <input type="date" name="school" class="form-control" value="<?php echo $DateLeaved; ?>">
                            <span class="help-block"><?php echo $DateLeaved_err;?></span>
                        </div>
						<div class="form-group <?php echo (!empty($gender_err)) ? 'has-error' : ''; ?>">
                            <label>Gender</label>
                            <input type="text" name="gender" class="form-control" value="<?php echo $gender; ?>">
                            <span class="help-block"><?php echo $gender_err;?></span>
                        </div>						
                        <input type="submit" class="btn btn-primary" value="Create">
                        <a href="index.php" class="btn btn-default">Cancel</a>
                    </form>
                </div>
            </div>        
</div> </div> </body> </html>

    The root cause is that you consistently do this in your HTML form: <input type="text" name="name". (The name value should be the the key you want it to be in the $_POST array).

    That being said, once you fix that, you should still not assume it's set, but check that it's there before you try to reference it.

    Lastly, please use this forum's [code]...[/code] tags around your code blocks.

    Oh, and welcome to the forums. 🙂

    NogDog I'm sorry the way I formatted the code. Thank you, I appreciated it!

      Sorry for how this sounds, but you have created a wall of code through repeatedly copy/pasting something you have seen, rather than actually leaning the meaning of what the code is doing, and it contains both mistakes (the undefined indexes are due to form field names that don't exist) and a huge amount of unnecessary variables and unnecessary logic.

      First learn how to do this using a single form field. Then, once you can design, write, test, and debug the code for one field, add the code needed for more than one field. Writing out code for all the form fields is a waste of time if you must then make changes to all of it before the code works.

      Writing out long lists of scalier/discrete variables is both error-prone and a waste of your time. If you had a form with 30 fields, would it be a good idea to create 60 different variables in your code? The submitted form data is a set of data, that will all be operated on in a same/similar way. Arrays are for sets of data. If you use an array for the errors and an array for the trimmed, working copy of the submitted data, you won't have to write out all those variables (you will also be able to dynamically process the submitted data - left as an advanced programming subject for you to work toward.) You would use elements in these two arrays in the rest of the code.

      Next, you need error handling for all the database statements where the actual error information will get displayed when learning, developing, and debugging, and will get logged when on a live public server. If you use exceptions for errors for the database statements and in most cases let php catch and handle the exception, php will use its error related settings to control what happens with the actual error information (database errors will 'automatically' get displayed/logged the same as php errors.)

        It looks like the posted code is trying to use mark-down/preformatted text, but it didn't work. Perhaps there's already some form of forum formatting in it and there's a mismatch now?

        Anyways, to enable exceptions for the mysqli extension, add the following line of code before the point where you make the database connection, and then remove any existing error handling logic -

        mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
        

        You should actually switch to the PDO extension, as it is much simpler and more consistent then the mysqli extension.

        See the following example that uses the suggestions I made above -

        <?php
        // Include connection file
        require_once "connect.php";
        
        // Define variables and initialize with empty values
        $post = []; // array to hold a trimmed, working copy of the submitted data
        $errors = []; // array to hold errors
        
        // Processing form data when form is submitted
        if($_SERVER["REQUEST_METHOD"] == "POST")
        {
        	$post = array_map('trim',$_POST); // trim all the data at once (if any of the fields are arrays, write a recursive trim call-back function to use here instead of php's trim function.)
        
        	// Validate firstname
        	if($post['firstname'] == '')
        	{
        		$errors['firstname'] = 'Please enter a First Name.';
        	} else if(!filter_var($post['firstname'], FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/[a-zA-Z\s]+$/"))))
        	{
        		$errors['firstname'] = 'The First Name can only contain letters and white-space.';
        	}
        
        	// add other validation here (after you get the code to work for a single form field)
        
        	// if no errors, use the submitted data
        	if(empty($errors))
        	{
        		// Prepare an insert statement
        		$sql = "INSERT INTO students_records (firstname) VALUES (?)";
        
        		// by using exceptions for errors, your code will only 'see' error free execution and there's no need for conditional logic at each statement unless your code will 'handle' an error that is 'recoverable' (such as inserting duplicate data)
        		$stmt = mysqli_prepare($link, $sql);
        		// Bind variables to the prepared statement as parameters - use the original variables, don't create variables for nothing
        		mysqli_stmt_bind_param($stmt, "s", $post['firstname']);
        		// Attempt to execute the prepared statement
        		mysqli_stmt_execute($stmt);
        	}
        	// if no errors at this point (allowing for the possibility of a user error from the database code), success
        	if(empty($errors))
        	{
        		// Record created successfully. Redirect to landing page
        		header("location: index.php");
        		exit();
        	}
        }
        
        ?>
        <!DOCTYPE html>
        <html lang="en">
        <head>
        <meta charset="UTF-8">
        <title>Create Record</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
        <style type="text/css">
        .wrapper{
        width: 500px;
        margin: 0 auto;
        margin-top: 0px;
        }
        </style>
        </head>
        <body>
        <div class="wrapper">
        <div class="container-fluid">
        <div class="row">
        <div class="col-md-12">
        <div class="page-header">
        <h2>Create Record</h2>
        </div>
        <p>Please fill this form and submit to add student record to the database.</p>
        <form method="post">
        <div class="form-group <?php echo !empty($errors['firstname']) ? 'has-error' : ''; ?>">
        <label>First Name</label>
        <input type="text" name="firstname" class="form-control" value="<?php echo $post['firstname'] ?? ''; ?>">
        <span class="help-block"><?php echo $errors['firstname'] ?? '';?></span>
        </div>
        <input type="submit" class="btn btn-primary" value="Create">
        <a href="index.php" class="btn btn-default">Cancel</a>
        </form>
        </div>
        </div>
        </div>
        </div>
        </body>
        </html>
          Write a Reply...