User Registration in PHP with Login: Form with MySQL and Code Download

by Vincy. Last modified on March 8th, 2023.

User registration with login is an essential component of a website. I will help you build a simple, lightweight user registration in PHP with login backed by MySQL database. Read on!

There are lots of PHP components for user registration available on the Internet. But these contain heavy stuff with lots of dependencies.

The code should be lightweight, secure, feature-packed, and customizable. The example you will see now will have these attributes and will be sufficient for any website.

User Registration in PHP with Login Form

What is inside?

  1. Example code for user registration in PHP
  2. Create user registration and login form
  3. Registration and login form validation
  4. Process user registration in PHP
  5. PHP login authentication code
  6. User dashboard
  7. MySQL database script
  8. Screenshot of user registration and login form

Example code for user registration in PHP

In this example, I have created user registration in PHP with the login script.

The landing page shows a login form with a signup link. The registered user can enter their login details with the login form. Once done, he can get into the dashboard after successful authentication.

If the user has no account, he can click the signup option to create a new one.

The user registration form requests a username, email and password from the user. On submission, the PHP code allows registration if the email does not already exist.

This example code has client-side validation for validating the entered user details. And also includes contains the server-side uniqueness test. The user email is the base to check uniqueness before adding the users to the MySQL database.

File structure

User Registration File Structure

Create a user registration and login form.

I have created three HTML views for the login, registration and dashboard in this code.

The below HTML code is for displaying the login form to the user. This form has two inputs to allow users to enter the username and password.

A validation code will not allow the login to proceed without these details. The login form tag’s on-click attribute is with loginValidation(). This function contains the login form validation script.

On submitting this login form, the PHP code will validate the user. If the users clear the authentication, it redirects to the dashboard.

If the user attempts to log in with the incorrect data, then the code will display a login error message in the login form. If you want to limit the failed login attempts, the linked article has an example.

See also the login form with forgot password and remember me for a complete suite of registration, login, forgot password and remember me options.

login.php

<?php
use Phppot\Member;

if (! empty($_POST["login-btn"])) {
    require_once __DIR__ . '/Model/Member.php';
    $member = new Member();
    $loginResult = $member->loginMember();
}
?>
<HTML>
<HEAD>
<TITLE>Login</TITLE>
<link href="assets/css/phppot-style.css" type="text/css"
	rel="stylesheet" />
<link href="assets/css/user-registration.css" type="text/css"
	rel="stylesheet" />
<script src="vendor/jquery/jquery-3.3.1.js" type="text/javascript"></script>
</HEAD>
<BODY>
	<div class="phppot-container">
		<div class="sign-up-container">
			<div class="login-signup">
				<a href="user-registration.php">Sign up</a>
			</div>
			<div class="signup-align">
				<form name="login" action="" method="post"
					onsubmit="return loginValidation()">
					<div class="signup-heading">Login</div>
				<?php if(!empty($loginResult)){?>
				<div class="error-msg"><?php echo $loginResult;?></div>
				<?php }?>
				<div class="row">
						<div class="inline-block">
							<div class="form-label">
								Username<span class="required error" id="username-info"></span>
							</div>
							<input class="input-box-330" type="text" name="username"
								id="username">
						</div>
					</div>
					<div class="row">
						<div class="inline-block">
							<div class="form-label">
								Password<span class="required error" id="login-password-info"></span>
							</div>
							<input class="input-box-330" type="password"
								name="login-password" id="login-password">
						</div>
					</div>
					<div class="row">
						<input class="btn" type="submit" name="login-btn"
							id="login-btn" value="Login">
					</div>
				</form>
			</div>
		</div>
	</div>

	<script>
function loginValidation() {
	var valid = true;
	$("#username").removeClass("error-field");
	$("#password").removeClass("error-field");

	var UserName = $("#username").val();
	var Password = $('#login-password').val();

	$("#username-info").html("").hide();

	if (UserName.trim() == "") {
		$("#username-info").html("required.").css("color", "#ee0000").show();
		$("#username").addClass("error-field");
		valid = false;
	}
	if (Password.trim() == "") {
		$("#login-password-info").html("required.").css("color", "#ee0000").show();
		$("#login-password").addClass("error-field");
		valid = false;
	}
	if (valid == false) {
		$('.error-field').first().focus();
		valid = false;
	}
	return valid;
}
</script>
</BODY>
</HTML>

Following is a user registration form to get minimal user data from the user. All form fields are mandatory.

It will pass through a JavaScript validation before processing the user registration in PHP.

On submitting the registration form fields, it will invoke the signupValidation() JavaScript method. This method validates with the non-empty check, email format, and password match.

After validation, the PHP registration will occur with the posted form data.

user-registration.php

<?php
use Phppot\Member;
if (! empty($_POST["signup-btn"])) {
    require_once './Model/Member.php';
    $member = new Member();
    $registrationResponse = $member->registerMember();
}
?>
<HTML>
<HEAD>
<TITLE>User Registration</TITLE>
<link href="assets/css/phppot-style.css" type="text/css"
	rel="stylesheet" />
<link href="assets/css/user-registration.css" type="text/css"
	rel="stylesheet" />
<script src="vendor/jquery/jquery-3.3.1.js" type="text/javascript"></script>
</HEAD>
<BODY>
	<div class="phppot-container">
		<div class="sign-up-container">
			<div class="login-signup">
				<a href="index.php">Login</a>
			</div>
			<div class="">
				<form name="sign-up" action="" method="post"
					onsubmit="return signupValidation()">
					<div class="signup-heading">Registration</div>
				<?php
    if (! empty($registrationResponse["status"])) {
        ?>
                    <?php
        if ($registrationResponse["status"] == "error") {
            ?>
				    <div class="server-response error-msg"><?php echo $registrationResponse["message"]; ?></div>
                    <?php
        } else if ($registrationResponse["status"] == "success") {
            ?>
                    <div class="server-response success-msg"><?php echo $registrationResponse["message"]; ?></div>
                    <?php
        }
        ?>
				<?php
    }
    ?>
				<div class="error-msg" id="error-msg"></div>
					<div class="row">
						<div class="inline-block">
							<div class="form-label">
								Username<span class="required error" id="username-info"></span>
							</div>
							<input class="input-box-330" type="text" name="username"
								id="username">
						</div>
					</div>
					<div class="row">
						<div class="inline-block">
							<div class="form-label">
								Email<span class="required error" id="email-info"></span>
							</div>
							<input class="input-box-330" type="email" name="email" id="email">
						</div>
					</div>
					<div class="row">
						<div class="inline-block">
							<div class="form-label">
								Password<span class="required error" id="signup-password-info"></span>
							</div>
							<input class="input-box-330" type="password"
								name="signup-password" id="signup-password">
						</div>
					</div>
					<div class="row">
						<div class="inline-block">
							<div class="form-label">
								Confirm Password<span class="required error"
									id="confirm-password-info"></span>
							</div>
							<input class="input-box-330" type="password"
								name="confirm-password" id="confirm-password">
						</div>
					</div>
					<div class="row">
						<input class="btn" type="submit" name="signup-btn"
							id="signup-btn" value="Sign up">
					</div>
				</form>
			</div>
		</div>
	</div>

	<script>
function signupValidation() {
	var valid = true;

	$("#username").removeClass("error-field");
	$("#email").removeClass("error-field");
	$("#password").removeClass("error-field");
	$("#confirm-password").removeClass("error-field");

	var UserName = $("#username").val();
	var email = $("#email").val();
	var Password = $('#signup-password').val();
    var ConfirmPassword = $('#confirm-password').val();
	var emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;

	$("#username-info").html("").hide();
	$("#email-info").html("").hide();

	if (UserName.trim() == "") {
		$("#username-info").html("required.").css("color", "#ee0000").show();
		$("#username").addClass("error-field");
		valid = false;
	}
	if (email == "") {
		$("#email-info").html("required").css("color", "#ee0000").show();
		$("#email").addClass("error-field");
		valid = false;
	} else if (email.trim() == "") {
		$("#email-info").html("Invalid email address.").css("color", "#ee0000").show();
		$("#email").addClass("error-field");
		valid = false;
	} else if (!emailRegex.test(email)) {
		$("#email-info").html("Invalid email address.").css("color", "#ee0000")
				.show();
		$("#email").addClass("error-field");
		valid = false;
	}
	if (Password.trim() == "") {
		$("#signup-password-info").html("required.").css("color", "#ee0000").show();
		$("#signup-password").addClass("error-field");
		valid = false;
	}
	if (ConfirmPassword.trim() == "") {
		$("#confirm-password-info").html("required.").css("color", "#ee0000").show();
		$("#confirm-password").addClass("error-field");
		valid = false;
	}
	if(Password != ConfirmPassword){
        $("#error-msg").html("Both passwords must be same.").show();
        valid=false;
    }
	if (valid == false) {
		$('.error-field').first().focus();
		valid = false;
	}
	return valid;
}
</script>
</BODY>
</HTML>

The landing page loads the login form.

index.php

<?php
require_once __DIR__ . "/login.php";

And the below CSS is for presenting this example of user registration.

user-registration.css

.sign-up-container {
	border: 1px solid;
	border-color: #9a9a9a;
	background: #fff;
	border-radius: 4px;
	padding: 10px;
	width: 350px;
	margin: 50px auto;
}

.page-header {
	float: right;
}

.login-signup {
	margin: 10px;
	text-decoration: none;
	float: right;
}

.login-signup a {
	text-decoration: none;
	font-weight: 700;
}

.signup-heading {
	font-size: 2em;
	font-weight: bold;
	padding-top: 60px;
	text-align: center;
}

.inline-block {
	display: inline-block;
}

.row {
	margin: 15px 0px;
	text-align: center;
}

.form-label {
	margin-bottom: 5px;
	text-align: left;
}

input.input-box-330 {
	width: 250px;
}

.sign-up-container .error {
	color: #ee0000;
	padding: 0px;
	background: none;
	border: #ee0000;
}

.sign-up-container .error-field {
	border: 1px solid #d96557;
}

.sign-up-container .error:before {
	content: '*';
	padding: 0 3px;
	color: #D8000C;
}

.error-msg {
	padding-top: 10px;
	color: #D8000C;
	text-align: center;
}

.success-msg {
    padding-top: 10px;
	color: #176701;
	text-align: center;
}

input.btn {
	width: 250px
}

.signup-align {
	margin: 0 auto;
}

.page-content {
	font-weight: bold;
	padding-top: 60px;
	text-align: center;
}

Registration and login form validation

I have used JavaScript to validate the form before submitting the request to the PHP backend.

On invalid data submission, the code will return a boolean false. It forces the user to enter the required fields by highlighting them.

Process user registration in PHP

After submitting the form details, it processes user registration in the PHP code.

This code uses the default form submission to post data to the PHP. If you want the user registration code with AJAX, we must prevent the default submission with a script.

I have added this code at the beginning of the user-registration-form.php. It checks if the user submitted the form. Then, it invokes the registerMember() method defined in the Member model.

I have shown the Member model class code below. It contains all the functions related to this user registration and login example.

The registerMember() function checks if the posted email already exists. If so, it truncates the registration flow and returns the error. Otherwise, it creates the Insert query to add the member record into the MySQL database.

The loginMember() function checks if there is any match for the entered login details. If the login match is found, it clears the authentication and allows the user to access the dashboard.

Model/Member.php

<?php
namespace Phppot;

class Member
{

    private $ds;

    function __construct()
    {
        require_once __DIR__ . '/../lib/DataSource.php';
        $this->ds = new DataSource();
    }

    /**
     * to check if the username already exists
     *
     * @param string $username
     * @return boolean
     */
    public function isUsernameExists($username)
    {
        $query = 'SELECT * FROM tbl_member where username = ?';
        $paramType = 's';
        $paramValue = array(
            $username
        );
        $resultArray = $this->ds->select($query, $paramType, $paramValue);
        $count = 0;
        if (is_array($resultArray)) {
            $count = count($resultArray);
        }
        if ($count > 0) {
            $result = true;
        } else {
            $result = false;
        }
        return $result;
    }

    /**
     * to check if the email already exists
     *
     * @param string $email
     * @return boolean
     */
    public function isEmailExists($email)
    {
        $query = 'SELECT * FROM tbl_member where email = ?';
        $paramType = 's';
        $paramValue = array(
            $email
        );
        $resultArray = $this->ds->select($query, $paramType, $paramValue);
        $count = 0;
        if (is_array($resultArray)) {
            $count = count($resultArray);
        }
        if ($count > 0) {
            $result = true;
        } else {
            $result = false;
        }
        return $result;
    }

    /**
     * to signup / register a user
     *
     * @return string[] registration status message
     */
    public function registerMember()
    {
        $isUsernameExists = $this->isUsernameExists($_POST["username"]);
        $isEmailExists = $this->isEmailExists($_POST["email"]);
        if ($isUsernameExists) {
            $response = array(
                "status" => "error",
                "message" => "Username already exists."
            );
        } else if ($isEmailExists) {
            $response = array(
                "status" => "error",
                "message" => "Email already exists."
            );
        } else {
            if (! empty($_POST["signup-password"])) {

                // PHP's password_hash is the best choice to use to store passwords
                // do not attempt to do your encryption, it is not safe
                $hashedPassword = password_hash($_POST["signup-password"], PASSWORD_DEFAULT);
            }
            $query = 'INSERT INTO tbl_member (username, password, email) VALUES (?, ?, ?)';
            $paramType = 'sss';
            $paramValue = array(
                $_POST["username"],
                $hashedPassword,
                $_POST["email"]
            );
            $memberId = $this->ds->insert($query, $paramType, $paramValue);
            if (! empty($memberId)) {
                $response = array(
                    "status" => "success",
                    "message" => "You have registered successfully."
                );
            }
        }
        return $response;
    }

    public function getMember($username)
    {
        $query = 'SELECT * FROM tbl_member where username = ?';
        $paramType = 's';
        $paramValue = array(
            $username
        );
        $memberRecord = $this->ds->select($query, $paramType, $paramValue);
        return $memberRecord;
    }

    /**
     * To login a user
     *
     * @return string
     */
    public function loginMember()
    {
        $memberRecord = $this->getMember($_POST["username"]);
        $loginPassword = 0;
        if (! empty($memberRecord)) {
            if (! empty($_POST["login-password"])) {
                $password = $_POST["login-password"];
            }
            $hashedPassword = $memberRecord[0]["password"];
            $loginPassword = 0;
            if (password_verify($password, $hashedPassword)) {
                $loginPassword = 1;
            }
        } else {
            $loginPassword = 0;
        }
        if ($loginPassword == 1) {
            // login sucess so store the member's username in
            // the session
            session_start();
            $_SESSION["username"] = $memberRecord[0]["username"];
            session_write_close();
            $url = "./home.php";
            header("Location: $url");
        } else if ($loginPassword == 0) {
            $loginStatus = "Invalid username or password.";
            return $loginStatus;
        }
    }
}

PHP login authentication code

The code in the login-form.php file above invokes the authentication function after login.

User dashboard

This is the user dashboard code. It shows a welcome message with the logged-in member name. It also has the option to log out from the current session.

At the top of the home.php file, I have done the session-based authorization check. This is to ensure that users who do not have access to this page are redirected to the login page.

If a not-logged-in user tries to access this page, the session will be cleared and he will be redirected to the login page.

home.php

<?php
session_start();
if (isset($_SESSION["username"])) {
    $username = $_SESSION["username"];
    session_write_close();
} else {
    // since the username is not set in session, the user is not-logged-in
    // he is trying to access this page unauthorized
    // so let's clear all session variables and redirect him to the index
    session_unset();
    session_write_close();
    $url = "./index.php";
    header("Location: $url");
}

?>
<HTML>
<HEAD>
<TITLE>Welcome</TITLE>
<link href="assets/css/phppot-style.css" type="text/css"
	rel="stylesheet" />
<link href="assets/css/user-registration.css" type="text/css"
	rel="stylesheet" />
</HEAD>
<BODY>
	<div class="phppot-container">
		<div class="page-header">
			<span class="login-signup"><a href="logout.php">Logout</a></span>
		</div>
		<div class="page-content">Welcome <?php echo $username;?></div>
	</div>
</BODY>
</HTML>

Logout

The following logout script is standard code. You can use it for any of your PHP projects. It clears the complete user session and redirects the user to the home/login page.

logout.php

<?php
// clear all the session variables and redirect to the index
session_start();
session_unset();
session_write_close();
$url = "./index.php";
header("Location: $url");

DataSource.php

This class is a wrapper for MySQL / MySQLi with the prepared statement. You can use it in any of your PHP and MySQL projects. It is available in the download project zip linked at the end of this tutorial.

MySQL database script

Below SQL script shows the MySQL database table’s create statement. It also has the specification for the key and indexes.

User registration MySQL schema

Import this script into your PHP development root to execute this example.

sql/user-registration.sql

--
-- Database: `user-registration`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_member`
--

CREATE TABLE `tbl_member` (
  `id` int(11) NOT NULL,
  `username` varchar(255) NOT NULL,
  `password` varchar(200) NOT NULL,
  `email` varchar(255) NOT NULL,
  `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_member`
--
ALTER TABLE `tbl_member`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_member`
--
ALTER TABLE `tbl_member`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

Screenshot of user registration and login form

Login form with validation response:

User Login Form Output

User registration form server-side validation response:

Screenshot User Registration PHP

Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “User Registration in PHP with Login: Form with MySQL and Code Download”

  • Chieki says:

    I’m impressed by your works

    I want to be proficient in PHP

    Teach me PHP proficiency.

    I’ll pay you.

    I’m not kidding.

  • natnael says:

    you are the best thanks a lot for providing such an outstanding tutorial and source code for us

  • francis says:

    nice tutorial vincy

  • Terry says:

    OUTSTANDING tutorial, easy to follow and looks to be very solid code.

    Any chance you could guide me on how to place approval on signup? In other words user must confirm email and then admin approves login afterwards.

    Love your site and is now on my weekly visit list:)

    • Vincy says:

      Hi Terry,

      Thank you for the nice words.

      I have got other articles that covers pretty much what you ask for. Browse through the left menu and you can find them out easily.

  • Raj says:

    Hi Vincy,

    Thank you. I am starting to learn php, your guides are helping me a very much.

    Thanks,
    Raj

  • pablo rotem says:

    one of the besst site ever!! i wish you could perhaps help me ut with an issue im trying to build in an open source project – please contact me if you are interested, and great job on your site !

  • rashmi says:

    Hi, awesome guide. Is it possible to use this guide and incorporate the OTP registration somehow?

    Regarding OTP code, how do I give option to either receive by SMS or email? For SMS OTP, what do I need to do to set it up?

    Thanks

    • Vincy says:

      Hi Rashmi,

      For OTP registration, you need to get service from a OTP service provider. Then use their API to integrate it.

  • Manpreet Singh says:

    Thanks you.
    Very nice article for PHP professional.

    I have successfully registered.

  • Sahmain says:

    May I ask what is the use of the $paramType = ‘s’?

  • Abhishek says:

    I want to become a good php developer, how can I start my journey?

    • Vincy says:

      Hi Abhishek,

      Choose a PHP book and learn it systematically. Then start developing a project and learn through coding.

  • Chittaranjan Ghosh says:

    AS usual your tutorials are really good to learn from.
    I was wondering if you use any framework for your projects, as it seems to me that you are confident enough in custom coding that hardly requires any framework.

    • Vincy says:

      Hi Ghosh,

      Thank you. I do not use frameworks as much as possible. I wish to code always in a light-weight way with lesser footprint.

  • Prof. Mbah Anthony says:

    I am developing a software with thousands of fieldsets whose inputs are submitted individually. Can you help me with the process? I’ll be glad if you can.

  • Mervin says:

    Wow…Vincy you simply magic. I am trying to create a savings and credit system. The rest of the system is almost done. And so far so good.

  • Jeff says:

    Not only is the really clean code, it’s well explained, and for me at least, nicely free of all sorts of other randomly confusing stuff, like depending on lots of huge libraries but only using a tiny bit of each library, which often makes it hard to see what is going on and what’s randomly extra. Thanks again, I am getting back into web development after many years away from it and your tutorials are very clear to me. Thanks again.

  • tony bonell says:

    Your code as an example helps too many people at all levels.

    thank you for your codes

  • Danish says:

    Hi Vincy,

    First of All I want to thank you I have learnt a lot in php because of you.

    Thanks,
    Danish

  • Moses says:

    Magnificent.

  • Yakub says:

    Hi, Thanks for the detailed tutorial.

    Thanks

  • Yakub says:

    Hi, I have tried and it is working.
    Thanks

  • emmy smith says:

    Really u are the best teacher , am glad with all that u have shared out here to us . remain bless.
    Really can u help , how can create a dashboard with this system where i can do CRUD operation from the dashboard for the users without going to the database to carry such operation. i will be happy u can help me out.i look forward hearing from u. Thank u

  • Parveen says:

    Hey thanks for the great file
    i am a beginner…
    Your given files are awesome, i have one doubt it will work in xamp or in the online direct…

    • Vincy says:

      Hi Parveen,

      Welcome. Yes, this code will work with Xampp. All you need is, Apache, PHP and MySQL.

  • Jon says:

    I can successfully register a user, thanks a lot

  • Abresh says:

    Its clean and simple. Also you applied OOP principles and PDO. Thank you for sharing your knowledge :) More visitors to come !

  • Ncc says:

    in login-form.php u are missing
    use Phppot\Member;

  • Bidemi says:

    Nice one Vincy. You’re a guru in this language. more power to your elbow.

  • MergimAlija says:

    I’m impressed, Vincy !
    Many thanks for the instruction and the code !

    Best regards,
    Mergim Alija

  • vijay says:

    this is very good post i like your every post….

    its kind of help for beginner to advance level of web developing…..

  • Rimpi saha says:

    Thank you

  • Claire says:

    How does the Log out on this form work? I can’t see any lines of code in login-form.php that would clear/end the session (but I am very new to this haha). Thanks!

  • mohamed says:

    good blog

  • Mb.a.k.a Joshua says:

    Marvelous work. Well commented and structured. Thanks for the source code too..

    • Vincy says:

      Hi Joshua,

      Thank you for explicitly calling it out. When effort on commenting and structuring gets noticed, I feel happy. Thank you.

  • yusuf says:

    thanks for the good job
    i would like to know does this code include validation in the email at the end of signing up?

  • Ojuaya says:

    So,so impressive!What a great work.I really learned a lot, thanks @Vincy

  • Khurram Raja says:

    ok after looking on a code i found that

    use Phppot\Member;

    is missing in login-form.php

    Please add this in the start same as registration php file.

    • Vincy says:

      Hi Khurram Raja,

      The complete code is updated and the latest version has use Phppot\Member

  • dennis says:

    A big help for a beginner like me and wants to continue my in progress in programming , i know programming must be good in mathematics Thanks for the author of this code

  • Chris says:

    Am very much impressed by this tutorial, thanks alot admin, as long as you will be here to answer our questions.

    I have been using WordPress, and they have a function called get_current_user_id();

    How can i create such function or get the details of the user that has logged in and viewing the dashboard using your code above?

    • Vincy says:

      Hi Chris,

      This project is written with plain PHP. To use this in WordPress, lot of changes should be done. If you are using WordPress, then you should probably using the login and registration provided with the CMS itself instead of building something custom.

  • Nichola says:

    Thanks for these works.
    The best free teacher and giver on the net..thumbs up !

  • Vimalraj says:

    Hello you are really great.
    Do you have any idea about JWT auth.

  • Tejas Borate says:

    Great bro your doing such a great work,I appreciated by your work…

  • Nora says:

    I’m using this script for my site, but it gives me connection error, the site has it own personal database so i use that, but it gives connection error…please help me, i have to write other codes or just the connection to the database to make the script work?

    • Vincy says:

      Hi Nora,

      Make sure you have set the database connection details in the DataSource.php

  • Hector says:

    I’m verry happy to found this blog, I’m co-founder, I hope work with you very soon! Thanks for sharing your knowledge.

  • Abbas B Mohammed says:

    You are awesome

  • Nitish says:

    You are making nice project in php.

  • Tauqir says:

    Hello, I’m a big fan of your codes.
    Thank you

  • Kapil says:

    Thank you, It is very helpful for me.
    Thanks a lot.

  • Corey says:

    I love everything about this site, detailed guide on various php jobs. Keep it up vicy

    But want know if there is way to keep the validation function in another page, and then called the function like this

    if(isset(‘submitbook’)) {
    echo book_validation ();
    }

    Does having both php and html in One page, poses a security

    • Vincy says:

      Hi Corey,

      Thank you. Sure, you can have both PHP and HTML on same page. It does not have any security issues. Having said that, try to separate the business logic and view as much as possible. It will help for maintenance and enhancements.

  • Bola says:

    Hello,
    thanks for this wonderful php projects…

  • Andy says:

    hello vincy, thanks for the code it’s working pretty well

  • raouani says:

    big thinks for all

  • Ifeoluwa Adenodi says:

    Hello brother
    I registered it was successful

  • kader says:

    HI,
    very nice job you doing, so thank you so much.

  • Jarvis says:

    How to set up database..?

    • Vincy says:

      Hi Jarvis,

      In the download bundle, there is a SQL file and it has the database structure. Import that file using PHPMyAdmin or any database client. Then your database is setup and ready.

  • Makoji Onate says:

    You’ve been most helpful on my journey to mastering Php…. I can’t thank you enough. I’m looking forward to crediting my work to you in the coming months when I’m finally able to compile my scripts and make them work perfectly. Thank you so big!

  • vishnu s nair says:

    Hi vincy,
    I just tried your script. It is fantastic.

  • Felix Okorie says:

    So glad to be here. Thanks for sharing your thoughts and knowledge with us.

  • Alex says:

    Nice work I’m impressed by your code and using it to learn php

  • Pushap Raj Verma says:

    First of all thanks for this. I am new for MySql. I don’t know how to. Will you please help me with this step. Thanks in advance.

  • satyam says:

    hi this is amazing

  • Shivam says:

    Great work.

    Thanks for creating the article.

  • adeel haider says:

    this tutorial is very helpful for me…..its amazing

  • hecctor says:

    Hello,
    Great work
    The zip file is missing though

  • Daniel says:

    Hi Vincy!

    Amazing tutorial. Thanks for sharing!

    One question,

    I uploaded the folder in my website just for testing, but when I click in sign up, show me 500 error. I changed the DataSource.php file and add my information (host, user, password and DBName) and still show the 500 error.

    Can you help me please?

  • Leo Istifanus says:

    wow! never knew php could be this easy. Kudos to you. thank you…

  • getake says:

    Vincy am new comer.. i appreciate ur work….

  • Borders says:

    Radical!

  • Mainul says:

    Thanks..

  • David says:

    How do I connect to the database

  • Chicken says:

    zero defect

  • Shagbaor Agber says:

    can i learn php and more from you??

  • Haisan Mohsen says:

    Great work

  • starFLEET says:

    Hi, Vincy thanks a lot for this tutorial.

  • John says:

    Oh my god this is so useful like literally MY REACTION WHEN THIS WORKED

  • Saurav Kumar says:

    Fatal error: Call to undefined function Phppot\password_hash() in C:\wamp\www\user-registration\Model\Member.php on line 91

  • Dondapati Kempu Chaitanya says:

    Very nice website , we want one website like teacheron pls consult me any one of you

  • Primeboss says:

    Gracias

  • Chonya Msafiri says:

    Thank you very much!!!

  • gamolive says:

    How will I view the login

  • Saurav says:

    Hii..this is showing plz help me

    Fatal error: Call to undefined function Phppot\password_hash() in C:\wamp\www\user-registration\user-registration\Model\Member.php on line 91

  • teemost says:

    hi vincy please i need you to assist me in php coding on my site. Please

  • Nikolay Tsekov says:

    thank you Vincy,
    nice work.

  • saravanan says:

    Great Job
    Thank you mam

  • Bharath says:

    nice work

  • Muhammad says:

    Thank you very much.
    I really gained alot

  • segun says:

    nice job

  • segun says:

    please Vincy can i get php code for comment and reply. thanks

  • Christoph says:

    Thank you so much for the code you supplied! I appreciate it so much!
    When I run the code, user-registration.php gives an error.
    The error_log shows this:

    [07-May-2021 09:46:15 Africa/Johannesburg] PHP Warning: call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object in /home/engincoz/eztermz/testing/login/lib/DataSource.php on line 165

    PHP Fatal error: Uncaught Error: Call to a member function execute() on bool in /home/engincoz/eztermz/testing/login/lib/DataSource.php:100

    seems to be this statement in dataSource.php giving problems:
    [165] call_user_func_array(array($stmt,’bind_param’), $paramValueReference);

    Any suggestions?

    • Vincy says:

      Hi Christoph,

      Looks like you have given the wrong username and password to connect to the database.

  • Louis says:

    Wow this is so good to be true, Thanks man

  • Ibrahim says:

    Nice work

  • Zenithgist says:

    What will be the URL to access the login page

    • Vincy says:

      Hi Zen,

      The URL to access the login form page is “user-registration/login-form.php”

  • abdul naufal says:

    its showing this errors how to solove this ?

    Warning: mysqli::__construct(): (HY000/1045): Access denied for user ‘root’@’localhost’ (using password: YES) in C:\xampp\htdocs\user-registration\lib\DataSource.php on line 56

    Notice: Problem with connecting to database. in C:\xampp\htdocs\user-registration\lib\DataSource.php on line 59

    Warning: mysqli::set_charset(): Couldn’t fetch mysqli in C:\xampp\htdocs\user-registration\lib\DataSource.php on line 62

    Warning: mysqli::prepare(): Couldn’t fetch mysqli in C:\xampp\htdocs\user-registration\lib\DataSource.php on line 94

    Warning: call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object in C:\xampp\htdocs\user-registration\lib\DataSource.php on line 167

    Fatal error: Uncaught Error: Call to a member function execute() on null in C:\xampp\htdocs\user-registration\lib\DataSource.php:100 Stack trace: #0 C:\xampp\htdocs\user-registration\Model\Member.php(28): Phppot\DataSource->select(‘SELECT * FROM t…’, ‘s’, Array) #1 C:\xampp\htdocs\user-registration\Model\Member.php(74): Phppot\Member->isUsernameExists(‘naufal’) #2 C:\xampp\htdocs\user-registration\user-registration.php(6): Phppot\Member->registerMember() #3 {main} thrown in C:\xampp\htdocs\user-registration\lib\DataSource.php on line 100

    • Vincy says:

      Hi Abdul,

      Looks like your database username and password is not correctly specified in Datasource.php

  • Ediwin says:

    OMG!

    This is the code i’ve looked for years! Thank you. It seems everything i need is right here. I’m happy, I’ve subscribed and I’ll share with others.

  • karthick says:

    Fatal error: Call to undefined function Phppot\password_hash() in C:\xampp\htdocs\login\Model\Member.php on line 91

    • Vincy says:

      Hi Karthick,

      You are have a very old version of PHP and you should upgrade to solve this issue.

  • Raju says:

    Hi, Vincy thanks a lot for this tutorial. I want forgot password page for this script. Please provide…

  • Sachithra says:

    Great work…Hey thank you… Can you help me to reset password in this website.

    • Vincy says:

      Hi Sachitra,

      Use the password recovery code posted earlier. Find the link in my reply @Raju above.

  • Roystan says:

    HI, thanks for the script. I installed it but issue when I tried to register a user. “Page is not working with HTTP Error 500”.Not sure where is the problem here. Can you help? thanks

  • Volker says:

    thank you so much Vincy. It saved me days of work.

  • Khalid says:

    Is this Script hack proof?

    • Vincy says:

      Hi Khalid,

      Yes, it uses PreparedStatement and protected from SQL injection issues.

  • Patrick says:

    wow!!! thank you Vincy i’m appreciated for your work and thank you for help me. God bless you.

  • John Rambo says:

    Nice work, I copy ur code and do some modification to meet my need. If possible, can I set the no activity session timeout? for example if no activity for 15 minutes, session will expired.

    • Vincy says:

      Hi John,

      Yes you can do that easily. When the user login, store the login timestamp and use the timediff and invalidate the user session.

  • Chenard says:

    hi,

    For some reason, I could not get it right. The page after registration came out blank. I know I make a mistake somewhere as it might due to not connecting to the mydatabasePHP or something.
    Any advice? Thank you

    • Vincy says:

      Hi Chenard,

      All you need to do is proper setup of database and specify the DB configuration in Datasource file and the user registration will happen without any issues.

  • john says:

    many thanks my friend GOD BLESS YOU

  • Miya says:

    Here, the registration form gets automatically submitted when the page refreshed. So, after a registration, if page is refreshed, it simply shows the error ‘Username already exists’. How to avoid this automatic resubmission of form happening when the page refreshes? Please help.

    • Vincy says:

      Hi Miya,

      You can redirect to a page after submission. In that case to display the succession message use session. Then this resubmission on refresh will not happen. This is a common pattern and solution.

      Either redirect or AJAX is the solution.

  • Ugochukwu Anusi says:

    Pls where should I place the DataSource.php File

  • nicholas says:

    hi vincy. Thanks a lot for this work. it helped me a lot!!
    though i’m having a small challenge. i tried to copy the code used to create users to help users insert data into the database when logged in. but i’m getting an error “PHP Warning: call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object in /../lib/DataSource.php on line 164”

    PHP Fatal error: Uncaught Error: Call to a member function execute() on boolean in /../lib/DataSource.php:127
    kindly assist

  • Dikz says:

    Such a great tutorial ❤️
    Thank You for making this.
    May god bless uh

  • Joabu Kaleme says:

    Wow thank you for share with us that ,

  • Frank says:

    Hello i used the code provided here where i use it on local host it works fine it redirects to home after a login but i uploaded it to 00webhost server when i log in it reloads the log in but doest redirect me to home welcome page but prompts a new log in what might be the issue

  • D’ Coder says:

    You are the best! Thank you very much.

  • Marc says:

    What software did you use for Php? :C

    • Vincy says:

      Hi Marc,

      I assume you are asking about editor?

      I use Eclipse and VIM in majority of situations.

  • Shah says:

    I’m a beginner in PHP and doing pet clinics system for final year project university. I want to use your code for guidance in PHP. Do I have to change the database name?
    Thank you for sharing your knowledge and great work.

    • Vincy says:

      Hi Shah,

      Yes, you should change the database name to what you already have in Datasource.php

  • Keza says:

    hello how can i do to display the email too after the username on the welcome page? thank you

    • Vincy says:

      In member.php, $_SESSION[“username”] = $memberRecord[0][“username”]; this line stores the username in session. You can use the same technique. Store the registered user’s email in session and get that in the welcome page and display it.

  • Alberto says:

    Greaaaaaaaaattttt…!!!!!
    you are special.
    ..
    I am from Argentina, I see ever your work, I like, congratulations for you and “MUCHA MUCHA SUERTE EN TU VIDA”.

  • Meka says:

    Excellent and simple script…THANK YA FOR CREATING IT!!!

  • Avinash says:

    Hi Vincy,

    How can i use this for aws

    • Vincy says:

      Hi Avinash,

      Can you give me more details on what way you want to use this in AWS? Do you want to deploy this code on AWS?

  • Emily Favour says:

    Thanks so much for this. I’m new to PHP but this help me so much. Please I want users to be redirected to a new page after successful registration rather than viewing the “You have registered successfully” message. How to I do that?
    Thanks in anticipation.

    • Vincy says:

      Hi Emily,

      Refer Member.php, public function loginMember() – this function and if ($loginPassword == 1) { this part of the if block takes care of redirecting the user after login. You can use that part and do redirect the user after registration.

  • Ebonge Pierre says:

    Thanks so much for this. I wish to have my users redirected to another page after successful registration. How do I do that?
    Thanks

    • Vincy says:

      Hi Pierre,

      In the file Model.php, there is a line that redirects after success “./home.php”. Change it to the file to which you want to redirect.

  • peter says:

    I get an error message when I try to download and run the codes. please help…

    Warning: mysqli::__construct(): (HY000/1045): Access denied for user ‘root’@’localhost’ (using password: YES) in E:\yerel\htdocs\lib\DataSource.php on line 56

    Notice: Problem with connecting to database. in E:\yerel\htdocs\lib\DataSource.php on line 59

    Fatal error: Uncaught Error: mysqli object is already closed in E:\yerel\htdocs\lib\DataSource.php:62 Stack trace: #0 E:\yerel\htdocs\lib\DataSource.php(62): mysqli->set_charset(‘utf8’) #1 E:\yerel\htdocs\lib\DataSource.php(45): Phppot\DataSource->getConnection() #2 E:\yerel\htdocs\Model\Member.php(12): Phppot\DataSource->__construct() #3 E:\yerel\htdocs\login.php(6): Phppot\Member->__construct() #4 E:\yerel\htdocs\index.php(2): require_once(‘E:\\yerel\\htdocs…’) #5 {main} thrown in E:\yerel\htdocs\lib\DataSource.php on line 62

    • Vincy says:

      Hi Peter,

      You need to supply the correct username and password to correct to the database.

  • Khalid says:

    You make it look so easy. Great stuff here. I can learn alot. Thank you.

  • shekhar says:

    nice for very help ful

  • alvaro says:

    hello I am using the code for “User Registration in PHP with Login: Form with MySQL and Code Download”, but when i press sign-in after filling out the form, the web page gives an error. the error page are: Warning: mysqli::__construct(): (HY000/1045): Access denied for user ‘root’@’localhost’ (using password: YES) in C:\xampp\htdocs\user-registration\lib\DataSource.php on line 56;
    Fatal error: Uncaught Error: mysqli object is already closed in C:\xampp\htdocs\user-registration\lib\DataSource.php:62 Stack trace: #0 C:\xampp\htdocs\user-registration\lib\DataSource.php(62);
    because? hope you can help me thanks

    • Vincy says:

      Hi Alvaro,

      Looks like your database configuration, username and password is not correct.

  • haritha says:

    hi why we used phppot in the first line can you please explain me

  • King Emmy says:

    Thanks for this bruh you really imapct knowledge on many of us

  • Thato says:

    Hi Thanks for your simple and easy to follow tutorials, if i wanted to use phone number instead of email can i just change the emails values to number? or would i have to start from scratch with input for numbers?

    • Vincy says:

      Hi Thato,

      Welcome. Using phone number in this registration and login is possible. But for validation, you need to send OTP and validate the phone number. To send OTP you will need access to a third-party API provider.

  • wilson says:

    How can I add product category and add products to a category and view categories and products in my inventory management system using Mysql dadabase?

    • Vincy says:

      Hi Wilson,

      Do you have a WordPress WooCommerce website? Can you give me more detail about your system. Send email with details and we can take it offline.

  • Davei.ii says:

    i have executed the file but this error keeps showin

    Warning: mysqli::__construct(): (HY000/1045): Access denied for user ‘root’@’localhost’ (using password: YES) in C:\xampp\htdocs\user-registration\user-registration\lib\DataSource.php on line 56

    Notice: Problem with connecting to database. in C:\xampp\htdocs\user-registration\user-registration\lib\DataSource.php on line 59

    Warning: mysqli::set_charset(): Couldn’t fetch mysqli in C:\xampp\htdocs\user-registration\user-registration\lib\DataSource.php on line 62

    Warning: mysqli::prepare(): Couldn’t fetch mysqli in C:\xampp\htdocs\user-registration\user-registration\lib\DataSource.php on line 94

    Warning: call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object in C:\xampp\htdocs\user-registration\user-registration\lib\DataSource.php on line 165

    Fatal error: Uncaught Error: Call to a member function execute() on bool in C:\xampp\htdocs\user-registration\user-registration\lib\DataSource.php:100 Stack trace: #0 C:\xampp\htdocs\user-registration\user-registration\Model\Member.php(28): Phppot\DataSource->select(‘SELECT * FROM t…’, ‘s’, Array) #1 C:\xampp\htdocs\user-registration\user-registration\Model\Member.php(74): Phppot\Member->isUsernameExists(‘davidongechi’) #2 C:\xampp\htdocs\user-registration\user-registration\user-registration.php(6): Phppot\Member->registerMember() #3 {main} thrown in C:\xampp\htdocs\user-registration\user-registration\lib\DataSource.php on line 100

    • Vincy says:

      Hi,

      Configure the database details host, username, password and database in the DataSource.php file.

Comments are closed.

↑ Back to Top

Share this page