0
0
PhpHow-ToBeginner · 4 min read

How to Create Registration Form in PHP with MySQL

To create a registration form in PHP with MySQL, build an HTML form to collect user data, then use PHP to process the form and insert the data into a MySQL database using mysqli or PDO. Make sure to validate inputs and securely hash passwords before saving.
📐

Syntax

The basic syntax involves three parts:

  • HTML form: Collects user inputs like username and password.
  • PHP script: Processes the form data, validates it, and connects to MySQL.
  • MySQL query: Inserts the validated data into the database.

Use mysqli_connect() to connect, password_hash() to secure passwords, and INSERT INTO SQL to save data.

php
<?php
// Connect to MySQL
$conn = mysqli_connect('localhost', 'username', 'password', 'database');

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

// Get form data
$username = $_POST['username'];
$password = $_POST['password'];

// Hash password
$hashed_password = password_hash($password, PASSWORD_DEFAULT);

// Insert query
$sql = "INSERT INTO users (username, password) VALUES ('$username', '$hashed_password')";

if (mysqli_query($conn, $sql)) {
    echo 'Registration successful';
} else {
    echo 'Error: ' . mysqli_error($conn);
}

mysqli_close($conn);
?>
💻

Example

This example shows a complete registration form with PHP processing that saves user data into a MySQL database. It includes input validation and password hashing for security.

php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Registration Form</title>
</head>
<body>

<?php
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $conn = mysqli_connect('localhost', 'root', '', 'testdb');
    if (!$conn) {
        die('Connection failed: ' . mysqli_connect_error());
    }

    $username = trim($_POST['username']);
    $password = $_POST['password'];

    if (empty($username) || empty($password)) {
        $message = 'Please fill in all fields.';
    } else {
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        $stmt = mysqli_prepare($conn, "INSERT INTO users (username, password) VALUES (?, ?)");
        mysqli_stmt_bind_param($stmt, 'ss', $username, $hashed_password);

        if (mysqli_stmt_execute($stmt)) {
            $message = 'Registration successful!';
        } else {
            $message = 'Error: ' . mysqli_error($conn);
        }

        mysqli_stmt_close($stmt);
    }

    mysqli_close($conn);
}
?>

<h2>Register</h2>
<form method="POST" action="">
    <label for="username">Username:</label><br>
    <input type="text" id="username" name="username" required><br><br>

    <label for="password">Password:</label><br>
    <input type="password" id="password" name="password" required><br><br>

    <input type="submit" value="Register">
</form>

<p><?php echo $message; ?></p>

</body>
</html>
Output
Register [Form with Username and Password fields and Register button] [Message area shows success or error after submission]
⚠️

Common Pitfalls

Common mistakes when creating a registration form with PHP and MySQL include:

  • Not validating or sanitizing user inputs, which can cause errors or security issues.
  • Storing passwords as plain text instead of hashing them securely.
  • Not using prepared statements, which can lead to SQL injection attacks.
  • Failing to check database connection errors.

Always validate inputs, hash passwords with password_hash(), and use prepared statements like mysqli_prepare().

php
<?php
// Wrong: Directly inserting user input (vulnerable to SQL injection)
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
mysqli_query($conn, $sql);

// Right: Using prepared statements and hashing password
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$stmt = mysqli_prepare($conn, "INSERT INTO users (username, password) VALUES (?, ?)");
mysqli_stmt_bind_param($stmt, 'ss', $username, $hashed_password);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
?>
📊

Quick Reference

  • Connect to MySQL: mysqli_connect(host, user, pass, db)
  • Hash passwords: password_hash(password, PASSWORD_DEFAULT)
  • Use prepared statements: mysqli_prepare(), mysqli_stmt_bind_param(), mysqli_stmt_execute()
  • Validate inputs: Check for empty fields and sanitize inputs.
  • Close connections: mysqli_close() after queries.

Key Takeaways

Always validate and sanitize user inputs before saving to the database.
Use password_hash() to securely store user passwords.
Use prepared statements to prevent SQL injection attacks.
Check and handle database connection errors properly.
Close database connections after completing queries.