User registration tutorial
Now a days, modern web applications need user registration features. In this user registration tutorial with php and MySQL, you will learn how to save user data into database.
Following tasks are performed in this tutorial.
- Setup the application
Create application folder
Install composer
Setup application
Create project folder structure - Create a MySQL database
- Create a HTML form for user registration
- Create User, Database classes to perform database operations
- Create an Image Upload class to upload user profile photos
- Create a script to insert data to the database
- Running the application
PHP, MySQL and phpMyAdmin should be installed on your system. Visit XAMPP or WAMP, and install it. After installation, start Apache and MySQL services.
1. Setup the application
- Create application folder
Open the www or htdocs folder in WAMP or XAMPP. Create a folder named php-mysql-registration-tutorial.
Open command line, and go to the application folder, type the command:
cd php-mysql-registration-tutorial
- Setup project using composer
Visit composer website, download and install. Follow the instructions. Open command line, type the command.
composer init
Select default options in the wizard. It will generate a composer.json. Replace the code below.
{ "autoload": { "psr-4": { "App\\": "src/" } } }
Install required dependencies.
composer install
This will install PSR-4 autoload package. Note the “App\\”: “src/” line in composer.json.
App is “Namespace” and src is the folder, where User, Database and Uploader classes are saved. Composer generates a Vendor folder and composer.lock file.
Create project folder structure
Open the project directory and create these folders.
- Create src folder
- Create inc folder
- Create assets folder, inside inc folder
- Create a css folder inside inc folder
- Create files folder inside assets folder. This folder is used to store profile pictures of users.
User registration form:
After setting up the folder structure, let’s create database and HTML form.
2. Create a MySQL database
Open PhpMyAdmin and create a database named dbuser.
http://localhost/phpmyadmin
CREATE DATABASE dbuser;
User table will have following fields:
- Id
- First name
- Last name
- Password
- Date of Birth
- Country
- Profile Photo of user
Create a table tbl_user, running the CREATE TABLE
command in SQL tab of phpMyAdmin.
CREATE TABLE `tbl_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(255) DEFAULT NULL, `last_name` varchar(250) DEFAULT NULL, `email` varchar(150) DEFAULT NULL, `password` varchar(128) DEFAULT NULL, `dob` date DEFAULT NULL, `country` varchar(255) DEFAULT NULL, `photo` varchar(300) DEFAULT NULL, `createdAt` datetime DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) );
2. Create classes for user registration tutorial
Let’s add classes in this user registration tutorial. Open the project folder in IDE like Visual Studio Code.
Create Database.php class
Create a file Database.php in src folder, and open it in the editor and add the code.
<?php namespace App; use PDO; class Database { private $host; private $user; private $password; private $database; private $dbconn; function __construct() { $this->host = 'localhost'; $this->user = 'root'; $this->password = ''; $this->database = 'dbuser'; $this->dbconn = null; } /** Connect to database */ public function connect() { try { $this->dbconn = new PDO('mysql:host='.$this->host.';dbname='.$this->database.'', $this->user, $this->password) or die("Cannot connect to MySQL."); // set the PDO error mode to exception $this->dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $this->dbconn; } catch(PDOException $e) { echo "Database connection failed: " . $e->getMessage(); die(); } } /** Insert user data into database */ public function insert($data) { $this->dbconn = $this->connect(); $password = sha1($data->getPassword()); $stmt = $this->dbconn->prepare("INSERT INTO tbl_user(first_name, last_name, email, password, dob, country, photo) VALUES (:first_name, :last_name, :email, :password, :dob, :country, :photo)"); $stmt->bindParam(':first_name', $data->getFirstName()); $stmt->bindParam(':last_name', $data->getLastName()); $stmt->bindParam(':email', $data->getEmail()); $stmt->bindParam(':password', $password); $stmt->bindParam(':dob', $data->getDob()); $stmt->bindParam(':country', $data->getCountry()); $stmt->bindParam(':photo', $data->getPhoto()); // insert a row if($stmt->execute()){ $result =1; } $this->dbconn = null; return true; } /** chek if email is unique or not */ public function checkUniquEmail($email) { $this->dbconn = $this->connect(); $query = $this->dbconn->prepare( "SELECT `email` FROM `tbl_user` WHERE `email` = :email" ); $query->bindValue(':email', $email ); $query->execute(); if($query->rowCount() > 0) { # If rows are found for query return true; } else { return false; } $this->dbconn = null; } }
Code explanation
In Database.php, first line is namespace App;
.
use PDO;
statement means, PHP’s PDO extension is used to access the database. The PDO or PHP Data Objects is a lightweight layer to access and perform CRUD tasks on database.
namespace App; use PDO;
Database class is created and, class properties like $host, $user, $password, $database and $dbconn are added. $dbconn is the connection object.
Constructor method is defined. This method gets called, when class object is instantiated. In constructor, the database host, user, password and database name are initialized.
class Database { private $host; private $user; private $password; private $database; private $dbconn; function __construct() { $this->host = 'localhost'; $this->user = 'root'; $this->password = ''; $this->database = 'dbuser'; $this->dbconn = null; } .....
The connect() method
Add a connect() method to connect to database. Inside a try{ ... } catch { ... }
statement, new PDO method is called.
public function connect() { try { $this->dbconn = new PDO('mysql:host='.$this->host.'dbname='.$this->database.'', $this->user, $this->password) or die("Cannot connect to MySQL."); // set the PDO error mode to exception $this->dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $this->dbconn; } catch(PDOException $e) { echo "Database connection failed: " . $e->getMessage(); die(); } }
If connection is successful, connection object is assigned to $this->dbconn otherwise an exception is thrown.
Insert method is created and it accepts $data object as parameter that contains user ‘s information.
The connect method is called to connect to database. In next line, getPassword() method is called from User class to get user entered password. Password is encrypted using sha1 encryption method.
The database connection’s prepare method is called. This method prepares a statement for execution and returns statement object.
Inside the prepare statement MySQL insert statement is used to add records to tbl_user. Placeholders are used to avoid SQL injection attacks.
The placeholder values are bind using statement object’s bindParam method like $stmt->bindParam(‘:first_name’, $data->getFirstName());.
/** Insert user data into database */ public function insert($data) { $this->connect(); $password = sha1($data->getPassword()); $stmt = $this->dbconn->prepare("INSERT INTO tbl_user(first_name, last_name, email, password, dob, country, photo) VALUES (:first_name, :last_name, :email, :password, :dob, :country, :photo)"); $stmt->bindParam(':first_name', $data->getFirstName()); $stmt->bindParam(':last_name', $data->getLastName()); $stmt->bindParam(':email', $data->getEmail()); $stmt->bindParam(':password', $password); $stmt->bindParam(':dob', $data->getDob()); $stmt->bindParam(':country', $data->getCountry()); $stmt->bindParam(':photo', $data->getPhoto()); // insert a row if($stmt->execute()){ $result = true;; } $this->dbconn = null; return $result; }
To insert data to the database, statement object’s execute method is called.
Check unique email method
This method validates if user entered email on signup form is unique or another user has already registered with the same email address.
/** chek if email is unique or not */ public function checkUniquEmail($email) { $this->connect(); $query = $this->dbconn->prepare( "SELECT `email` FROM `tbl_user` WHERE `email` = :email" ); $query->bindValue(':email', $email ); $query->execute(); if($query->rowCount() > 0) { # If rows are found for query return true; } else { return false; } $this->dbconn = null; }
Create User.php class
Add a file User.php in src folder and open in editor.
Namespace is defined first, and DB class is included from App namespace.
<?php /** * @description: User class create a new user. */ namespace App; use App\DB; class User { private $first_name; private $last_name; private $email; private $password; private $confirm_password; private $dob; private $country; private $photo; private $error; /** Assign the data to properties */ public function __construct($user) { $this->first_name = $user['first_name']; $this->last_name = $user['last_name']; $this->email = $user['email']; $this->password = $user['password']; $this->confirm_password = $user['conf_password']; $this->dob = $user['dob']; $this->country = $user['country']; $this->terms = $user['terms']; $this->error = null; } public function setPhoto($photo) { $this->photo = $photo; } /** Validate user entered data */ public function validate(){ /** Validate Name */ if (!$this->first_name || !$this->last_name) { $this->error .= "<li>First and Last name are mandatory.</li>"; } /** Validate Email */ if(!$this->email) { $this->error .= "<li>Email cannot be left blank.</li>"; } elseif (!strpos($this->email, '@') || !strpos($this->email, '.')) { $this->error .= "<li>Enter a valid email.</li>"; } else { $db = new database(); if($db->checkUniquEmail($this->email)) { $this->error .= "<li>Email already exists!. Try another.</li>"; } } /** Validate Password */ if (!$this->password || !$this->confirm_password) { $this->error .= "<li>Password and confirm password are required.</li>"; } elseif(strlen($this->password) <6){ $this->error .= "<li>Password must be atleast 6 characters long.</li>"; } elseif($this->password !== $this->confirm_password) { $this->error .= "<li>Password and confirm password donot match</li>"; } /** Validate Date of Birth */ if (!$this->dob) { $this->error .= "<li>Date of Birth is mandatory.</li>"; } /** Validate Date of Birth */ if (!$this->country) { $this->error .= "<li>Country is mandatory.</li>"; } /** Validate Terms */ if (!$this->terms) { $this->error .= "<li>Please accept terms and conditions</li>"; } return $this->error; } public function getFirstName() { return $this->first_name; } public function getLastName() { return $this->last_name; } public function getEmail() { return $this->email; } public function getPassword() { return $this->password; } public function getDob() { return $this->dob; } public function getCountry() { return $this->country; } public function getPhoto() { return $this->photo; } //insert into database a new user public function insert() { $db = new database(); return $db->insert($this); } }
User class is create and inside class private properties like $first_name, $last_name etc. are declared.
The class constructor accepts $user array and assigns to first_name, last_name and other properties.
Set photo method
public function setPhoto($photo) { $this->photo = $photo; }
The setPhoto method is used to set the image name uploaded by the user.
Validate method for user registration tutorial
Data is validated before saving to database. Following validations are preformed
- First and last name are mandatory
- Email is mandatory and is valid
- Password and confirm password are mandatory and are minimum 6 characters in length
- Date of birth is mandatory
- Country is mandatory
- User accepts the term and conditions
Getter methods for class properties
To access class private properties, getter methods are created, like getFirstName(). This method will return first name of user.
public function getFirstName() { return $this->first_name; }
Image upload class
To upload user profile image, uplaoder class is created. Beside other methods, there is a method uplaod_file. Uploaded file is moved to directory using move_uplaoded_file method.
function upload_file(){ $uploadTo = "uploads/"; $allowFileType = array('jpg','png','jpeg','gif','pdf','doc'); $fileName = $_FILES['file']['name']; $tempPath=$_FILES["file"]["tmp_name"]; $basename = basename($fileName); $originalPath = $uploadTo.$basename; $fileType = pathinfo($originalPath, PATHINFO_EXTENSION); if(!empty($fileName)){ if(in_array($fileType, $allowFileType)){ // Upload file to server if(move_uploaded_file($tempPath,$originalPath)){ return $fileName." was uploaded successfully"; }else{ $error = 'File Not uploaded ! try again'; } }else{ return $fileType." file type not allowed"; } }else{ return "Please Select a file"; } }
In upload class there are methods to validate uploaded image, assign a unique name to the file and other utility methods.
Create HTML form for user registration tutorial
let’s create HTML form to get data from user.
Create header.php file
Open inc folder, add a file header.php.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:400,700"> <title>User Registration Tutorial Using PHP and MySQL</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="inc/assets/css/style.css"> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> </head> <body>
In header.php file, the CSS and JavaScript files are included.
Add a style.css file
Open css folder inside inc folder in assets folder. Add file style.css.
body { color: #fff; background: #63738a; font-family: 'Roboto', sans-serif; } .form-control { height: 40px; box-shadow: none; color: #969fa4; } .form-control:focus { border-color: #5cb85c; } .form-control, .btn { border-radius: 3px; } .signup-form { width: 450px; margin: 0 auto; padding: 30px 0; font-size: 15px; } .signup-form h2 { color: #636363; margin: 0 0 15px; position: relative; text-align: center; } .signup-form h2:before, .signup-form h2:after { content: ""; height: 2px; width: 30%; background: #d4d4d4; position: absolute; top: 50%; z-index: 2; } .signup-form h2:before { left: 0; } .signup-form h2:after { right: 0; } .signup-form .hint-text { color: #999; margin-bottom: 30px; text-align: center; } .signup-form form { color: #999; border-radius: 3px; margin-bottom: 15px; background: #f2f3f7; box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); padding: 30px; } .signup-form .form-group { margin-bottom: 20px; } .signup-form input[type="checkbox"] { margin-top: 3px; } .signup-form .btn { font-size: 16px; font-weight: bold; min-width: 140px; outline: none !important; } .signup-form .row div:first-child { padding-right: 10px; } .signup-form .row div:last-child { padding-left: 10px; } .signup-form a { color: #fff; text-decoration: underline; } .signup-form a:hover { text-decoration: none; } .signup-form form a { color: #5cb85c; text-decoration: none; } .signup-form form a:hover { text-decoration: underline; }
Create footer.php file
In inc folder, add a file footer.php and add code.
</body> </html>
Create index.php file
Open project folder. Create a file index.php. This file includes use statements. Namespaces are used to include the User and Uploader classes.
Next, we check that if the form is submitted by user by using if(isset($_POST[‘submit’])) { … }.
The user entered values are assigned to an array. The User class object is created and assigned to $userObj;
$userObj = new User($user); $error = $userObj->validate(); if (!is_uploaded_file($_FILES['photo']['tmp_name'])){ $error .= "<li>Profile photo cannot be left blank.</li>"; }
Errors are returned to $error variable after validate() method is called.
If there is no error then an Uploader file object is created. Destination directory, extensions and image sizes are set.
$uploader->uploadFile('photo')
method is used to upload the file to destination directory. After uploading the file, the $uploader->getUploadName()
method is used to get the uploaded file name.
After getting the upload file name, it is set to user object with setPhoto method.
After data validation and uploading the profile photo to the server, insert method is called. User data is inserted and flag is set to true.
<?php use App\User; use App\Uploader; include_once('inc/header.php'); include_once('vendor/autoload.php'); $directory = 'inc/assets/files/'; $user = []; $flag = false; if(isset($_POST['submit'])) { $user['first_name'] = $_POST['first_name']; $user['last_name'] = $_POST['last_name']; $user['email'] = $_POST['email']; $user['password'] = $_POST['password']; $user['conf_password'] = $_POST['conf_password']; $user['dob'] = $_POST['dob']; $user['country'] = $_POST['country']; $user['terms'] = $_POST['terms'] ?? null; /** Create user object, validate and insert into database */ $userObj = new User($user); $error = $userObj->validate(); if (!is_uploaded_file($_FILES['photo']['tmp_name'])){ $error .= "<li>Profile photo cannot be left blank.</li>"; } if(!$error) { $uploader = new Uploader(); $uploader->setDir($directory); $uploader->setExtensions(array('jpg','jpeg','png','gif')); //allowed extensions list// $uploader->setMaxSize(1); //set max file size to be allowed in MB// if($uploader->uploadFile('photo')){ $image = $uploader->getUploadName(); //get uploaded file name, renames on upload// $userObj->setPhoto($image); } else{ $uploader->getMessage(); //get upload error message } $result = $userObj->insert(); $flag = true; } } ?> <div class="signup-form"> <form method="post" action="index.php" enctype="multipart/form-data"> <h2>Register</h2> <p class="hint-text">Create your account. It is free and only takes a minute.</p> <div class="form-group"> <?php if(isset($error)): ?> <div class="row"> <div class="form-group"> <div class="alert alert-danger" role="alert"> <ul> <?=$error ?> </ul> </div> </div> </div> <?php elseif($flag): ?> <div class="row"> <div class="form-group"> <div class="alert alert-success" role="alert"> Registration successfull. Click here to login </div> </div> </div> <?php endif; ?> <div class="row"> <div class="col"><input required <?php if(isset($user['first_name'])) { echo 'value="'.$user['first_name'].'"'; } ?> type="text" class="form-control" name="first_name" placeholder="First Name" ></div> <div class="col"><input required <?php if(isset($user['last_name'])) { echo 'value="'.$user['last_name'].'"'; } ?> type="text" class="form-control" name="last_name" placeholder="Last Name" ></div> </div> </div> <div class="form-group"> <input type="email" required <?php if(isset($user['email'])) { echo 'value="'.$user['email'].'"'; } ?> class="form-control" name="email" placeholder="Email" > </div> <div class="form-group"> <input type="password" required <?php if(isset($user['password'])) { echo 'value="'.$user['password'].'"'; } ?> class="form-control" name="password" placeholder="Password" > </div> <div class="form-group"> <input type="password" required <?php if(isset($user['conf_password'])) { echo 'value="'.$user['conf_password'].'"'; } ?> class="form-control" name="conf_password" placeholder="Confirm Password" > </div> <div class="form-group"> <input type="date" required <?php if(isset($user['dob'])) { echo 'value="'.$user['dob'].'"'; } ?> class="form-control" name="dob" placeholder="Date of Birth" > </div> <div class="form-group"> <input type="text" required <?php if(isset($user['country'])) { echo 'value="'.$user['country'].'"'; } ?> class="form-control" name="country" placeholder="Country" > </div> <div class="form-group"> <input type="file" required class="form-control" name="photo" placeholder="Your Photo"> </div> <div class="form-group"> <label class="form-check-label"><input required <?php if(isset($user['terms'])) { echo 'checked'; } ?> type="checkbox" name="terms"> I accept the <a href="#">Terms of Use</a> & <a href="#">Privacy Policy</a></label> </div> <div class="form-group"> <input type="submit" name="submit" class="btn btn-success btn-lg btn-block" value="Register Now"> </div> </form> <div class="text-center">Already have an account? <a href="#">Sign in</a></div> </div> <?php include_once('inc/footer.php'); ?>
Let’s add a form with following fields:
- First name
- Last name
- Password
- Date of Birth
- Country
- Terms & Conditions checkbox
div class="signup-form"> <form method="post" action="index.php" enctype="multipart/form-data"> <h2>Register</h2> <p class="hint-text">Create your account. It is free and only takes a minute.</p> <div class="form-group"> <?php if(isset($error)): ?> <div class="row"> <div class="form-group"> <div class="alert alert-danger" role="alert"> <ul> <?=$error ?> </ul> </div> </div> </div> <?php elseif($flag): ?> <div class="row"> <div class="form-group"> <div class="alert alert-success" role="alert"> Registration successful. Click here to login </div> </div> </div> <?php endif; ?> <div class="row"> <div class="col"><input required <?php if(isset($user['first_name'])) { echo 'value="'.$user['first_name'].'"'; } ?> type="text" class="form-control" name="first_name" placeholder="First Name" ></div> <div class="col"><input required <?php if(isset($user['last_name'])) { echo 'value="'.$user['last_name'].'"'; } ?> type="text" class="form-control" name="last_name" placeholder="Last Name" ></div> </div> </div> <div class="form-group"> <input type="email" required <?php if(isset($user['email'])) { echo 'value="'.$user['email'].'"'; } ?> class="form-control" name="email" placeholder="Email" > </div> <div class="form-group"> <input type="password" required <?php if(isset($user['password'])) { echo 'value="'.$user['password'].'"'; } ?> class="form-control" name="password" placeholder="Password" > </div> <div class="form-group"> <input type="password" required <?php if(isset($user['conf_password'])) { echo 'value="'.$user['conf_password'].'"'; } ?> class="form-control" name="conf_password" placeholder="Confirm Password" > </div> <div class="form-group"> <input type="date" required <?php if(isset($user['dob'])) { echo 'value="'.$user['dob'].'"'; } ?> class="form-control" name="dob" placeholder="Date of Birth" > </div> <div class="form-group"> <input type="text" required <?php if(isset($user['country'])) { echo 'value="'.$user['country'].'"'; } ?> class="form-control" name="country" placeholder="Country" > </div> <div class="form-group"> <input type="file" required class="form-control" name="photo" placeholder="Your Photo"> </div> <div class="form-group"> <label class="form-check-label"><input required <?php if(isset($user['terms'])) { echo 'checked'; } ?> type="checkbox" name="terms"> I accept the <a href="#">Terms of Use</a> & <a href="#">Privacy Policy</a></label> </div> <div class="form-group"> <input type="submit" name="submit" class="btn btn-success btn-lg btn-block" value="Register Now"> </div> </form> <div class="text-center">Already have an account? <a href="#">Sign in</a></div> </div> <?php include_once('inc/footer.php'); ?>
After form is created, include footer.php.
Running the application
In order to run the application, make sure Apache and MySQL services are running. Open the browser, type the URL in address bar
http://localhost/php-mysql-registration-tutorial/
After filling in all the data, click Register Now button.
Summary:
To summarize, In this user registration tutorial, you have learnt to create a MySQL database and table. Then, created an HTML form with php classes and inserted user data to the database.
You can find the source code of the tutorial on our GitHub Repository. Clone or download the project in htdocs or www root folder and run in browser.
If you liked this tutorial, subscribe to our newsletter and follow us on Twitter, or like our Facebook page.
Learning Resources:
Here are some best resources to learn PHP & MySQL
PHP MYSQL Full Stack Web Developer Course
The Complete 2021 PHP Full Stack Web Developer Bootcamp
Learn to build websites with HTML, CSS, JAVASCRIPT, Bootstrap, PHP, MySQL, WordPress, OOP & more!
PHP MySQL Professional Course
The Complete PHP MYSQL Professional Course with 5 Projects
Related Articles:
- Php PDO and jQuery AJAX tutorial with example source code
- Php mysqli tutorial for beginners with example source code