A REGISTER AND LOGIN FORM IN PHP AND MYSQL

This is the simple method to create a user registration and login system using PHP and MySQL.
Steps to Follow:
1. Create a Database – Store user information.
2. Build a Registration Page – Allow users to sign up.
3. Create a Login Page – Allow users to log in.
4. Implement Session Management – Keep users logged in.
Step 1: Create MySQL Database and Table
Run this SQL command to create a database and users table:
CREATE DATABASE user_system;
USE user_system;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
email VARCHAR(100) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL
);
<?php
$host = "localhost";
$user = "root"; // Change if using a different username
$pass = ""; // Change if you set a password
$dbname = "user_system";
$conn = new mysqli($host, $user, $pass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<?php
include 'db.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$email = $_POST['email'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$sql = "INSERT INTO users (username, email, password) VALUES (?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $username, $email, $password);
if ($stmt->execute()) {
echo "Registration successful. <a href='login.php'>Login here</a>";
} else {
echo "Error: " . $conn->error;
}
}
?>
<form method="post">
Username: <input type="text" name="username" required><br>
Email: <input type="email" name="email" required><br>
Password: <input type="password" name="password" required><br>
<button type="submit">Register</button>
</form>
<?php
include 'db.php';
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
if ($user && password_verify($password, $user['password'])) {
$_SESSION['username'] = $user['username'];
header("Location: dashboard.php");
exit;
} else {
echo "Invalid username or password.";
}
}
?>
<form method="post">
Username: <input type="text" name="username" required><br>
Password: <input type="password" name="password" required><br>
<button type="submit">Login</button>
</form>
<?php
session_start();
if (!isset($_SESSION['username'])) {
header("Location: login.php");
exit;
}
echo "Welcome, " . $_SESSION['username'] . "!";
?>
Logout
<?php
session_start();
session_destroy();
header("Location: login.php");
exit;
?>
Date: 2025-04-03 00:00:00.000000