In this article we’re going to take a look at basic form validation of form submitted via PHP. The basis of this is to cover backend validation or server-side validation. This should be key to any web development project and you should always implement server-side validation at a bare minimum. Consideration should be made here before you move to frontend validation, which we will cover later in the series.
Before we get started you will need the following in place
A working web server
Access to a MySQL database
The ability to create tables using an IDE such as MySQL Workbench
An existing form which submits data to a MySQL database (you can follow our Form Submission guide first if you don’t already have this 😁)
In order to get started with this task we need a form to work from, you can create this form by following the Form Submission guide which is also part of this section on developerspace.co.uk. The code we’re going to use for this is listed below, but bear in mind that you can implement server-side validation in any HTML & PHP form - the form is essentially irrelevant at this stage.
create.php
<form action="" method="POST">
<label for="product">Product Name</label>
<input type="text" name="product" value="">
<label for="price">Product Price</label>
<input type="text" name="price" value="">
<label for="description">Product Name</label>
<textarea name="description"></textarea>
<button>Save Product</button>
</form>
<?php
if($_SERVER['REQUEST_METHOD'] === "POST") {
// check that we have data sent to us
if(isset($_POST['product']) && isset($_POST['price']) && isset($_POST['description'])) {
$servername = "databaseserver.co.uk";
$username = "yourusername";
$password = "yourpassword";
$database = "yourdatabasename";
try {
// attempt to connect to the server
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// collect the data into variables for easier access later
$product = $_POST['product'];
$price = $_POST['price'];
$description = $_POST['description'];
// build the MySQL statement
$mysql = "INSERT INTO product (product, price, description) VALUES ( '$product', '$price', '$description' )";
// pass the query back to PDO
$newproduct = $conn->prepare($mysql);
// run the query
$newproduct->execute();
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
}
}
?>
The basis of this article is to provide simple validation, what this means is that we’re going to prevent our users from entering any silly data into our system whether this is intentional or entirely accidental.
It would be worth at this stage making sure you’re familiar with the GIGO concept, which stands for Garbage In Garbage Out. In short if we allow random data to be input into our systems database when we come to process that data we’re going to get results which are anomalistic or misleading (“garbage”).
Another key reason we need to cover this is for security concerns, the most common methods of systems being breached remains some of those which have been around for decades, consider an SQL Injection attack for example.
The validation we’re going to be adding to this form is basic, it has a job to uphold which is to keep our system safe and to prevent any random data being entered. We’re going to implement this validation using if statements.
We’re going to concentrate on the PHP section of the code in this case. This is the code (from the above code sample) we will concentrate on.
try {
// attempt to connect to the server
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// collect the data into variables for easier access later
$product = $_POST['product'];
$price = $_POST['price'];
$description = $_POST['description'];
// build the MySQL statement
$mysql = "INSERT INTO product (product, price, description) VALUES ( '$product', '$price', '$description' )";
// pass the query back to PDO
$newproduct = $conn->prepare($mysql);
// run the query
$newproduct->execute();
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
Breaking this down further there are 3 lines which specifically collect data from our form submission. These lines are…
// collect the data into variables for easier access later
$product = $_POST['product'];
$price = $_POST['price'];
$description = $_POST['description'];
We’re going to start with the input of a product name which is achieved on the 2nd line of the code block above. In this case we can set out a number of rules we expect a product name to abide by like below.
Looking at these rules we can start to identify what we need to put in place in order to protect our database and system which is ultimately what the user is interacting with. We’re going to achieve this by using multiple if statements at this stage.
Anyone familiar with programming concepts will be able to identify an if statement. They are fairly syntactically similar in most languages whether C++ or PHP. They allow us to check for a condition and if the condition is true (or in some cases false) trigger the next block of code. Below we will implement an if statement to check that the product name has actually been submitted.
// collect the data into variables for easier access later
$product = $_POST['product'];
$price = $_POST['price'];
$description = $_POST['description'];
// check that the product name sent isn't empty
if(isset($product)) {
// the product name has been sent so continue with other code here
}
In this case we’re checking that it has been submitted we’re not necessarily checking if it’s blank or empty. Let’s expand that rule to check if the user has submitted a blank product name.
// collect the data into variables for easier access later
$product = $_POST['product'];
$price = $_POST['price'];
$description = $_POST['description'];
// check that the product name sent isn't empty
if( isset($product) && strlen($product) > 3 ) {
// the product name has been sent so continue with other code here
}
In this case we’ve added some additional code within the existing if statement condition. Which looks like this.
&& strlen($product) > 3
The && indicates that we want to check something else, we then follow this up with strlen which will check the length of some entered information - in this case the product name. We’re then carrying out some logic which checks that the length of the text is more than 3 characters long.
There are other things we can do here, your best bet is to have a look at the PHP documentation which is fantastic and includes a whole range of built-in functions which we can use to check our submission. Some which may come in useful are:
At the moment if we don’t pass our very simple validation rules then nothing will be displayed on the screen so there are few ways we can combat this, the easiest way is to add an else to our if statement making it and if else statement. Let’s have a look at what that would look like…
// collect the data into variables for easier access later
$product = $_POST['product'];
$price = $_POST['price'];
$description = $_POST['description'];
// check that the product name sent isn't empty
if( isset($product) && strlen($product) > 3 ) {
// the product name has been sent so continue with other code here
}
else {
$error = "You need to submit a valid product name";
}
An alternative method would be to log each error which has occurred into an array which you will use to display all form errors back to the user at the same time. This is much more functional and user friendly.
// blank array to store errors
$error = array();
// collect the data into variables for easier access later
$product = $_POST['product'];
$price = $_POST['price'];
$description = $_POST['description'];
// check that the product name sent isn't empty
if( isset($product) && strlen($product) > 3 ) {
// the product name has been sent so continue with other code here
}
else {
$error[] = "You need to submit a valid product name";
}
With the $error[] syntax we’re able to push each error into the array. Let’s have a look at an example that features more than one rule. In this case we’ve reversed the rules to make our code more streamlined. In the example below we’re saying if the product name is not sent and the product name is less than 4 characters in length then add an error to the $error array. We have indicated this for the isset option by prefixing it with an exclamation mark (!) which essentially says IS NOT.
// blank array to store errors
$error = array();
// collect the data into variables for easier access later
$product = $_POST['product'];
$price = $_POST['price'];
$description = $_POST['description'];
// check that the product name sent isn't empty
if( !isset($product) && strlen($product) <= 3 ) {
$error[] = "You need to submit a valid product name";
}
// we would continue to the next block of code if this is satisfied
if( !is_string($product) ) {
$error[] = "You need to submit a valid string!";
}
In this case we’re not actually stopping any wrong doing we’re just logging errors. So to stop the code actually continuing if there is an error we need to check for errors. To do this we can add the following code.
if(count($error) > 0) {
// loop the errors and show them on screen
foreach($error as $error_message) {
echo $error_message;
}
}
else {
// process the form and add the data to the database
}
Let’s have a look at what that would all look like together now then.
// blank array to store errors
$error = array();
// collect the data into variables for easier access later
$product = $_POST['product'];
$price = $_POST['price'];
$description = $_POST['description'];
// check that the product name sent isn't empty
if( !isset($product) && strlen($product) <= 3 ) {
$error[] = "You need to submit a valid product name";
}
// check that the product entered is a valid string
if( !is_string($product) ) {
$error[] = "You need to submit a valid string!";
}
// check if any errors have occured
if(count($error) > 0) {
// loop the errors and show them on screen
foreach($error as $error_message) {
echo $error_message;
}
}
else {
// validation has passed insert the product
$mysql = "INSERT INTO product (product_name, price) VALUES ( '$product_name', '$product_price')";
$products = $conn->prepare($mysql);
$products->execute();
}
Now there are alternatives, this is a basis to get you started. This is not the be all and end all of form validation by any means but it does show you the concepts and how you can implement basic rules which could protect your application in PHP.