Sign Up

Tutorial to create a login system using HTML, PHP, and MySQL

This is a tutorial for creating a login system with the help of HTML, PHP, and MySQL. Your website needs to be dynamic and your visitors need to have instant access to it. Therefore, they want to log in as many times as possible. The login authentication system is very common for any web application. It allows registered users to access the website and members-only features. It is also helpful when we want to store information for users. It covers everything from shopping sites, educational sites, and membership sites, etc.

This tutorial is covered in 4 parts.

Table of Contents

1) Building a Signup system

In this part, We will create a signup system that allows users to create a new account to the system. Our first step is to create a HTML registration form. The form is pretty simple to create. It only asks for a name, email, password, and confirm password. Email addresses will be unique for every user. Multiple accounts for the same email address are not allowed. It will show an error message to the users who try to create multiple accounts with the same email address.

Читайте также:  Merge sort сортировка слиянием python

Step 1: Creating Registration Form in HTML

We will create a PHP file named register.php with the following code in it. This is a simple HTML form with some basic validation. If you are not familiar with HTML then you can get it from many online sites who give ready-made html5 login form templates.

       

Register

Please fill this form to create an account.

Already have an account? Login here.

The output of the above HTML form will look like this.

Sign Up

All the input fields are required by adding the «required» attribute which is the default HTML attribute. The use of type=»email» will validate the email address provided by users and gives an error if the email address is not valid. For the registration form, we have used bootstrap for rapid development. If you want to save your time on HTML code you can always use some free html5 templates for your project.

Step 2: Creating the MySQL Database Table

You will need to create a new database with any suitable name you want. After that please execute the below SQL query to create the user’s table inside your newly created MySQL database.

CREATE TABLE `users` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(75) NOT NULL, `password` varchar(255) NOT NULL, `email` varchar(100) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;

Step 3: Creating Database Configuration File

Now, we have created the users table. Let’s create a new PHP file named config.php to connect with the MySQL database. Paste the following code in the config.php file and change the database name to whatever you choose while creating the database.

Step 4: Creating a Session File

Let’s create a file named session.php. In this file, we will start the session and check if a user is already logged in, if yes then we will redirect the user to welcome.php file.

Step 5: Create Registration Form in PHP

Finally, it’s time to create a PHP code that allows users to register their accounts into the system. This PHP code will alert users with an error if any user is already registered with the same email address.

Replace the following code in the register.php file.

prepare("SELECT * FROM users WHERE email = ?")) < $error = ''; // Bind parameters (s = string, i = int, b = blob, etc), in our case the username is a string so we use "s" $query->bind_param('s', $email); $query->execute(); // Store the result so we can check if the account exists in the database. $query->store_result(); if ($query->num_rows > 0) < $error .= '

The email address is already registered!

'; > else < // Validate password if (strlen($password ) < 6) < $error .= '

Password must have atleast 6 characters.

'; > // Validate confirm password if (empty($confirm_password)) < $error .= '

Please enter confirm password.

'; > else < if (empty($error) && ($password != $confirm_password)) < $error .= '

Password did not match.

'; > > if (empty($error) ) < $insertQuery = $db->prepare("INSERT INTO users (name, email, password) VALUES (?, ?, ?);"); $insertQuery->bind_param("sss", $fullname, $email, $password_hash); $result = $insertQuery->execute(); if ($result) < $error .= '

Your registration was successful!

'; > else < $error .= '

Something went wrong!

'; > > > > $query->close(); $insertQuery->close(); // Close DB connection mysqli_close($db); > ?>

Register

Please fill this form to create an account.

Already have an account? Login here.

Once user click on submit button it will check if $_SERVER[«REQUEST_METHOD»] == «POST» and $_POST[‘submit’] variable has been set. For security concerns, we always suggest not to store the password as plain text in the database. We have used password_hash() function which creates a new password hash using a strong one-way hashing algorithm.

The above PHP script will validate that no user is registered with the same email address and also validate password. After validation is confirmed we store the user-provided information in the users’ table and alert the user that registration was successful.

2) Building a Login System

In this part, we will create a login form to allow users to access the restricted area of the system. In our case, the restricted area is a welcome page which we will cover in the next part.

Step 1: Creating a Login Form in HTML

Below is the Login Form in HTML. Paste it in a file named login.php

       

Login

Please fill in your email and password.

Don't have an account? Register here.

The output of the above code will look like this

Login

Step 2: Creating a Login System in PHP

After creating the login form in HTML, we will write a code to validate login credentials. On form submit we will check that the email and password are filled. If they filled then we will execute a SELECT query to find the record in a database on the basis of email and password. If any record found, then we will store the «userID» in session and the user is redirected to the welcome.php file, otherwise, the user is alerted with an error message.

Let’s replace the following code in the login.php file.

Please enter email.

'; > // validate if password is empty if (empty($password)) < $error .= '

Please enter your password.

'; > if (empty($error)) < if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) < $query->bind_param('s', $email); $query->execute(); $row = $query->fetch(); if ($row) < if (password_verify($password, $row['password'])) < $_SESSION["userid"] = $row['id']; $_SESSION["user"] = $row; // Redirect the user to welcome page header("location: welcome.php"); exit; >else < $error .= '

The password is not valid.

'; > > else < $error .= '

No User exist with that email address.

'; > > $query->close(); > // Close connection mysqli_close($db); > ?>

Login

Please fill in your email and password.

Don't have an account? Register here.

3) Creating a Welcome Page

Below is the code for the welcome.php file. Users will be redirected to this page after a successful login process. We have added some code at the top of the page to check if the user is not logged in, then redirect the user to the login page.

Let’s create a welcome.php file and paste the following code in it.

 ?>    Welcome   

Hello, . Welcome to demo site.

Log Out

4) The Logout script

Finally, Let’s create a logout.php file with the following code in it.

Once the user clicks on the Log Out link, the above script, will be called to destroy the session and redirect user to the login.php file.

Conclusion

In this tutorial, I explained how you can create a Login System using HTML, PHP and MySQL. Once you understand how simple it is to create a login system you can add other features like reset password, forgot password, verify email address, edit user’s profile, etc.

Источник

How to connect an HTML form to a MySQL database in PHP

Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.

This Answer outlines how to use PHP to connect an HTML form to a MySQL database. We’ll use XAMPP as the server software to create a database and run PHP.

We’ll use the below steps to create a connection:

  1. Set up XAMPP and configure a PHP development environment
  2. Create an HTML form
  3. Create a MySQL database
  4. Create a PHP file
  5. Create a connection

Step 1: Set up XAMPP

The method to configure a PHP development environment with XAMPP is shown here.

Step 2: Create an HTML form

This Answer explains what an HTML form is and how to create it.

Step 3: Create a MySQL database

In this step, we’ll create a simple MySQL database since our server is already running.

We’ll open the browser and type http://localhost/phpmyadmin/. This redirects us to the PHP admin page, where we can create and manage databases. Click on the New option in the menu panel on the left side. The image below demonstrates this:

On the next page, we’ll choose a name for our database and click on Create, as shown:

Next, we’ll create a table in the database. We’ll add a table name and choose the number of columns:

Once we click on Create, we’ll be redirected to the following page:

Here, we’ve to give details regarding the table. The columns correspond to our fields in the HTML form. We may also assign each column a data type, characters length, or special privileges such as the primary A unique identifier for each entry in a table. key. A sample table is as follows:

Once we’re done, we’ll click on Save. Our first table in the database is created.

Step 4: Create a PHP file

Now that we have our database and server ready, we’ll create the necessary files. We’ll begin by opening the folder directory containing XAMPP. We traditionally find this folder in Local Disk E or Local Disk C. For Linux users, this will be in the Computer/opt/lampp directory.

Within that folder, open another folder titled htdocs and create a folder in it. We can name it anything, but for this tutorial, we’ll name it educativeform . This new folder will contain our HTML and PHP files.

htdocs/educativeform
|-> form.php
|-> index.html

The following code snippet contains the HTML code for the form:

Note: If we click on the submit button, it will given an error since we haven’t yet connected it to the database.

Explanation

  • Line 6: The method POST is the connection type to send the HTML form entries. The action attribute has the value form.php . This is the name of the PHP file in the working directory, and the form entries will be sent to this file upon submission.
  • Lines 8–20: These are the form fields. The last input type is a button that submits the field values to the PHP file.

To confirm that our form is ready, we’ll type localhost/educativeform in the browser. This ensures that the server, MySQL, and Apache is running. Otherwise, we might get an error.

Next, we’ll create the PHP file. The sample code, along with the explanation, is given below:

if(isset($_POST['submit']))
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
>
?>

Explanation

  • Line 2: We’ll use the $_POST as connection type to get HTML form entries.
  • Lines 4–6: We define the fields here. The square brackets contain the values of the name attribute in the input labels of the HTML code.

Step 5: Create a connection

Finally, we’ll connect our HTML form to the database using PHP. The code below is an addition to the previous code snippet, as shown:

// getting all values from the HTML form
if(isset($_POST['submit']))
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
>
// database details
$host = "localhost";
$username = "root";
$password = "";
$dbname = "sampledb";
// creating a connection
$con = mysqli_connect($host, $username, $password, $dbname);
// to ensure that the connection is made
if (!$con)
die("Connection failed!" . mysqli_connect_error());
>
// using sql to create a data entry query
$sql = "INSERT INTO contactform_entries (id, fname, lname, email) VALUES ('0', '$fname', '$lname', '$email')";
// send query to the database to add values and confirm if successful
$rs = mysqli_query($con, $sql);
if($rs)
echo "Entries added!";
>
// close connection
mysqli_close($con);
?>

Explanation

  • Lines 10–14: We’ll specify the permissions of the database. This will allow us to add entries to the table.
  • Line 17: We use mysqli_connect to create a connection.
  • Lines 20–23: Here, we’ll confirm if the connection is made. If the connection has failed, we’ll get an error message.
  • Line 26: We create an SQL query for insertion. Here we add the values that we received from the HTML form.
  • Lines 29–33: We send the query to the database over the connection.
  • Line 36: This line closes the connection once the entry is inserted.

If everything is running without errors, we should be able to add our HTML form details in the MySQL database.

Learn in-demand tech skills in half the time

Источник

Оцените статью