In this stage we will process the incoming form submissions to insert rows into the database. The previous two stages must be completed first (Create Database from MySQL Console and Creating the Web Form).
1. Create a new file in the same folder as your index.php
file called process_my_form.php
. This script will be run when someone submits the form from the previous stage. Open the new file for editing in Visual Studio Code.
2. Add html
and body
tags and a PHP tag inside the body.
3. Copy the input values received from the form into their own variables. They are all saved in the $_GET
superglobal associative array, where the keys are the values of the name attributes of the <input>
elements in the HTML form.
$firstName = $_GET["first_name"];
$lastName = $_GET["last_name"];
4. Create a variable to track the validation. You can use an array to store the validation of each field, but start with just a yes or no boolean variable. Initially it will be true, and validation checks will try to make it false.
$isValid = true;
5. Add a length check for the first name. Make sure it is less than 20 characters long.
if (strlen($firstName) >= 20) {
$isValid = false;
}
6. Add a presence check for the last name.
if (empty($lastName)) {
$isValid = false;
}
7. If the validation succeeded, add a record to the database with an INSERT
query.
if ($isValid) {
$databaseLink = new mysqli("localhost", "root", "", "NeatTreats");
$databaseLink->query(
"INSERT INTO Customer(FirstName, LastName)" .
"VALUES ($firstName, $lastName);"
);
$databaseLink->close();
}
8. Otherwise, if the validation failed, output an error and a link back to the form.
} else {
echo "<p>Could not add record due to invalid input</p>";
echo "<a href='index.php'>Go Back</a>";
}
The final code should look like this:
<html><body><?php
$firstName = $_GET["first_name"];
$lastName = $_GET["last_name"];
$isValid = true;
if (strlen($firstName) >= 20) $isValid = false;
if (empty($lastName)) $isValid = false;
if ($isValid) {
$databaseLink = new mysqli("localhost", "root", "", "NeatTreats");
$databaseLink->query(
"INSERT INTO Customer(FirstName, LastName)" .
"VALUES ($firstName, $lastName);"
);
$databaseLink->close();
echo "<p>You were added to our database!</p>";
} else {
echo "<p>Could not add record due to invalid input</p>";
echo "<a href='index.php'>Try again</a>";
}
?></body></html>
Parent topic: Example 2
Top comments (0)