Simple User Registration With PHP MYSQL (Free Download)

Welcome to a tutorial on how to create a simple user registration system with PHP MySQL. Want to open your website for user registrations? It’s not really that difficult, let us walk through a simple registration system in this guide – Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TABLE OF CONTENTS

Download & Notes User Register Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • Create a database and import 1-users.sql.
  • Edit 2-user-lib.php, change the database settings to your own.
  • Launch 3-register.php in the browser.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

USER REGISTRATION

All right, let us now walk through the simple PHP MYSQL user registration.

 

PART 1) USER DATABASE

1-users.sql
CREATE TABLE `users` (
  `user_id` int(11) NOT NULL,
  `user_name` varchar(255) NOT NULL,
  `user_email` varchar(255) NOT NULL,
  `user_password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
 
ALTER TABLE `users`
  ADD PRIMARY KEY (`user_id`),
  ADD UNIQUE KEY `user_email` (`user_email`);
 
ALTER TABLE `users`
  MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;T

First, we are going to need a user table, here is a simple one.

  • user_id Primary key, auto-increment.
  • user_name The user’s name.
  • user_email The user’s email. Set to unique to prevent duplicate registrations.
  • user_password Captain Obvious, the password.

 

 

PART 2) USER LIBRARY

2-user-lib.php
<?php
class Users {
  // (A) CONSTRUCTOR - CONNECT TO DATABASE
  private $pdo = null;
  private $stmt = null;
  public $error = null;
  function __construct () {
  try {
    $this->pdo = new PDO(
      "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET,
      DB_USER, DB_PASSWORD, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
      ]);
    } catch (Exception $ex) { exit($ex->getMessage()); }
  }
 
  // (B) DESTRUCTOR - CLOSE DATABASE CONNECTION
  function __destruct () {
    if ($this->stmt !== null) { $this->stmt = null; }
    if ($this->pdo !== null) { $this->pdo = null; }
  }
 
  // (C) RUN SQL QUERY
  // $sql : sql to run
  // $data : data to bind
  function query ($sql, $data=null) {
    $this->stmt = $this->pdo->prepare($sql);
    $this->stmt->execute($data);
  }
 
  // (D) GET USER BY ID OR EMAIL
  // $id : email or user id
  function get ($id) {
    $this->query(sprintf("SELECT * FROM `users` WHERE `user_%s`=?",
      is_numeric($id) ? "id" : "email"
    ), [$id]);
    return $this->stmt->fetch();
  }
 
  // (E) REGISTER USER
  // $name : user name
  // $email : user email
  // $pass : password
  function register ($name, $email, $pass) {
    // (E1) CHECK
    if (is_array($this->get($email))) {
      $this->error = "$email is already registered";
      return false;
    }
 
    // (E2) ADD NEW USER
    try {
      $this->query(
        "INSERT INTO `users` (`user_name`, `user_email`, `user_password`) VALUES (?,?,?)",
        [$name, $email, password_hash($pass, PASSWORD_DEFAULT)]
      );
      return true;
    } catch (Exception $ex) {
      $this->error = $ex->getMessage();
      return false;
    }
  }
}
 
// (F) DATABASE SETTINGS - CHANGE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8");
define("DB_USER", "root");
define("DB_PASSWORD", "");
 
// (G) CREATE USER OBJECT
$USR = new Users();

With the database in place, the next step is to build a user library to work with it. This looks complicated at first, but keep calm and look carefully.

  1. The constructor automatically connects to the database when $USR = new Users() is created.
  2. The destructor closes the connection when $USR is destroyed.
  3. query() A helper function to run an SQL statement.
  4. get() Get user with the given user ID or email.
  5. register() Register user.

 

 

PART 3) REGISTRATION PAGE

THE HTML

3-register.php
<?php
/* (A) ALREADY SIGNED IN - TO HOME PAGE
if (isset($_SESSION["user"])) {
  header("Location: HOME.PAGE");
  exit();
}
*/
 
// (B) PROCESS REGISTRATION
if (count($_POST)>0) {
  require "2-user-lib.php";
  $pass = $USR->register($_POST["name"], $_POST["email"], $_POST["pass"]);
  if ($pass) {
    // header("Location: HOME.PAGE");
    exit("SUCCESSFUL!");
  }
}
 
// (C) REGISTRATION FORM ?>
<!DOCTYPE html>
<html>
  <head>
    <title>User Registration</title>
    <link rel="stylesheet" href="3-register.css"/>
    <script src="3-register.js"></script>
  </head>
  <body>
    <!-- (C1) ERROR MESSAGE (IF ANY) -->
    <?php
    if (isset($pass) && $pass==false) {
      echo "<div class='error'>$USR->error</div>";
    } ?>
 
    <!-- (C2) REGISTRATION FORM -->
    <form method="post" id="reg-form" onsubmit="return check()">
      <h2>REGISTER</h2>
      <input type="text" name="name" placeholder="Name" required value="Jon"/>
      <input type="email" name="email" placeholder="Email" required value="jon@doe.com"/>
      <input type="password" name="pass" placeholder="Password" required value="12345"/>
      <input type="password" name="cpass" placeholder="Confirm Password" required value="12345"/>
      <input type="submit" value="Register"/>
    </form>
  </body>
</html>

The process order here is a little jumbled, but here’s how it works:

  • (C2) The HTML registration form.
  • (B) Process the registration form when it is being submitted. Redirect the user to a “welcome” or home page after a successful registration.
  • (C1) Show the error message, if the registration fails.
  • (A) Enable this section after you are done with the login. If the user is already signed in, redirect to the home page, or whatever page you want.

 

 

THE JAVASCRIPT

3-register.js
function check () {
  let pass = document.getElementsByName("pass")[0].value,
  cpass = document.getElementsByName("cpass")[0].value;
  if (pass != cpass) {
    alert("Passwords do not match");
    return false;
  } else { return true; }
}

Just a small bit to check if the passwords match. I will recommend doing this on the server-side though (in the PHP library register()), along with a password strength check.

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

HOW ABOUT THE USER LOGIN?

To verify the password, simply get the user from the database and do a password check – if (password_verify($_POST["password"], DATABASE PASSWORD)) { OK - LOGIN }. But the login mechanism is another story.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published.