This is a simple tutorial that will teach you on how to create a simple registration form using PHP/MySQL using PDO Query and server-side error validation. This tutorial will not teach you on how to create a good design but rather to give you knowledge on how to create a fully functional registration form. This tutorial is different from my previous registration page tutorial. To find out what's the difference, follow the steps bellow
Creating Our Database
First we are going to create our database which stores our data.
To create a database:
1. Open phpmyadmin
2. Then create database and name it as "pdo_ret".
3. After creating a database name, click the SQL and paste the following code.
CREATE TABLE IF NOT EXISTS `members` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`fname` varchar(100) NOT NULL,
`lname` varchar(100) NOT NULL,
`age` int(5) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Creating The Form
Next step is to create a form and save it as index.php. The code bellow include the code that display the error validation generated by the server. To create a form, open your HTML code editor and paste the code below after the tag.
<?php
?>
<?php
if( isset($_SESSION['ERRMSG_ARR']) && is_array($_SESSION['ERRMSG_ARR']) && count($_SESSION['ERRMSG_ARR']) >0 ) {
echo '<ul style="padding:0; color:red;">';
foreach($_SESSION['ERRMSG_ARR'] as $msg) {
echo '<li>',$msg,'</li>';
}
echo '</ul>';
unset($_SESSION['ERRMSG_ARR']);
}
?>
<form action="reg.php" method="POST">
First Name<br>
<input type="text" name="fname" /><br>
Last Name<br>
<input type="text" name="lname" /><br>
Age<br>
<input type="text" name="age" /><br>
<input type="submit" value="Save" />
</form>
Writing Our Save Script
Next step is to create our script that save our input data to database and save it as "reg.php". The code bellow contains server-side validation and the save scripts.
<?php
$errflag = false;
// configuration
$dbhost = "localhost";
$dbname = "pdo_ret";
$dbuser = "root";
$dbpass = "";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];
if($fname == '') {
$errmsg_arr[] = 'You must enter your First Name';
$errflag = true;
}
if($lname == '') {
$errmsg_arr[] = 'You must enter your Last Name';
$errflag = true;
}
if($age == '') {
$errmsg_arr[] = 'You must enter your Age';
$errflag = true;
}
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
header("location: index.php");
}
// query
$sql = "INSERT INTO members (fname,lname,age) VALUES (:sas,:asas,:asafs)";
$q = $conn->prepare($sql);
$q->execute(array(':sas'=>$fname,':asas'=>$lname,':asafs'=>$age));
header("location: index.php");
?>
That's it! You've been successfully created your simple registration form with PDO Query and server-side validation.