php
  1. php-mysql-login-system

PHP MySQL Login System

Syntax

//DB Connection
$con = mysqli_connect($servername,$username,$password,$db);

//Query for verifying user credentials
$query = "SELECT * FROM users WHERE email = '$email' AND password = '$password'";

$result = mysqli_query($con,$query);

//Check if user exists
if(mysqli_num_rows($result) == 1){
    //Login Successful
}
else{
    //Login Failed
}

Example

<?php

$servername = "localhost";
$username = "root";
$password = "";
$db = "mydatabase";

// Create connection
$con = mysqli_connect($servername, $username, $password, $db);

// Check connection
if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}

//Variables to store form data
$email = $_POST['email'];
$password = $_POST['password'];

//Query for verifying user credentials
$query = "SELECT * FROM users WHERE email = '$email' AND password = '$password'";

$result = mysqli_query($con,$query);

//Check if user exists
if(mysqli_num_rows($result) == 1){
    //Login Successful
    session_start();
    $_SESSION['email'] = $email;
    header("Location: homepage.php");
}
else{
    //Login Failed
    echo "Invalid Email or Password";
}

mysqli_close($con);
?>

Output

If the email and password match with a record in the 'users' table of the database, the user is redirected to a homepage. Otherwise, an error message is displayed.

Explanation

This code snippet demonstrates a basic PHP MySQL login system. A database connection is established using the mysqli_connect() function. User inputs for email and password are obtained using the $_POST superglobal variable and are used in a query to verify user credentials. If the query returns a row, it indicates that the user exists and the login is successful. Session variables are set to store user information for future use. If the user does not exist or invalid credentials are entered, an error message is displayed.

Use

This code snippet can be used as a starting point to create a secure and scalable login system for a website or web application.

Important Points

  • It is important to hash passwords before storing them in the database.
  • Session variables should be used instead of storing sensitive user information in cookies.
  • Form inputs should be validated to prevent SQL injection attacks.

Summary

The PHP MySQL Login System is a crucial feature for website or web application, and this code snippet provides a basic implementation of the same. It includes code to establish a database connection, verify user credentials, and handle successful/failed logins. This code can be customized and extended to meet the specific requirements of different projects.

Published on: