PHP MySQL Creating a user registration form
Creating a user registration form using PHP MySQL in procedural style involves several key steps: building an HTML form to collect user details, validating and sanitizing the inputs, inserting the data into a MySQL database, and providing feedback on the registration process. Below is a step-by-step guide to accomplish this:
Steps:
- Create a registration form (HTML).
- Handle the form submission in PHP.
- Validate and sanitize user input.
- Hash the password for security.
- Insert the data into the database.
- Provide user feedback.
Example: User Registration Form
1. HTML Form (for User Registration)
Create an HTML form to collect user details like username, email, and password.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Registration</title>
</head>
<body>
<h2>User Registration</h2>
<form action="register.php" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Register">
</form>
</body>
</html>
2. PHP for Handling Registration (register.php
)
- Database connection.
- Validate and sanitize inputs.
- Hash the password.
- Insert into the database.
Here’s the PHP code to handle the registration:
<?php
// Check if the form was submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Step 1: Capture and sanitize the input data
$username = trim($_POST['username']);
$email = trim($_POST['email']);
$password = trim($_POST['password']);
// Sanitize input
$username = filter_var($username, FILTER_SANITIZE_STRING);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Step 2: Validate input
if (empty($username) || empty($email) || empty($password)) {
die("All fields are required.");
}
// Validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
die("Invalid email format.");
}
// Step 3: Hash the password (for security)
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// Step 4: Establish a MySQL connection
$servername = "localhost";
$db_username = "root";
$db_password = "";
$dbname = "test_db";
// Create a connection
$conn = mysqli_connect($servername, $db_username, $db_password, $dbname);
// Check the connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Step 5: Prepare an SQL query to insert the user data
$sql = "INSERT INTO users (username, email, password) VALUES ('$username', '$email', '$hashed_password')";
// Step 6: Execute the query
if (mysqli_query($conn, $sql)) {
echo "User registered successfully!";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
// Close the connection
mysqli_close($conn);
}
?>
3. Create the Database Table
Ensure that your MySQL database has a table to store the user registration details.
CREATE DATABASE test_db;
USE test_db;
CREATE TABLE users (
id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Explanation:
Sanitizing Input: The
filter_var()
function is used to sanitize and validate the form data. For example, it ensures that the email is in a valid format and strips out any invalid characters.Password Hashing: For security reasons, the password is hashed using PHP’s
password_hash()
function, which securely hashes the password before storing it in the database. You can later usepassword_verify()
to check the password during login.Database Connection: A connection to the MySQL database is established using
mysqli_connect()
. Always check if the connection is successful.SQL Query: The sanitized and hashed user data is inserted into the MySQL database using the
INSERT INTO
query. The query is executed usingmysqli_query()
.User Feedback: After the form submission, feedback is provided based on whether the registration was successful or not.
Security Considerations:
SQL Injection Prevention: In this example, raw data is inserted directly into the query. For better security, it’s recommended to use prepared statements with
mysqli_prepare()
andmysqli_stmt_bind_param()
to prevent SQL injection attacks.Password Security: Always hash the password before storing it in the database.
password_hash()
uses a strong, one-way hashing algorithm with a salt, ensuring that even if the database is compromised, the passwords are difficult to crack.HTTPS: Always use HTTPS to transmit sensitive information like passwords securely.
Using Prepared Statements for Security
Here’s an enhanced version of the PHP script using prepared statements:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = trim($_POST['username']);
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$username = filter_var($username, FILTER_SANITIZE_STRING);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (empty($username) || empty($email) || empty($password)) {
die("All fields are required.");
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
die("Invalid email format.");
}
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$conn = mysqli_connect("localhost", "root", "", "test_db");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Use prepared statement
$stmt = mysqli_prepare($conn, "INSERT INTO users (username, email, password) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($stmt, "sss", $username, $email, $hashed_password);
if (mysqli_stmt_execute($stmt)) {
echo "User registered successfully!";
} else {
echo "Error: " . mysqli_stmt_error($stmt);
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
?>
This version prevents SQL injection by using prepared statements and parameterized queries. It’s a much more secure way of handling user data, especially when interacting with a database.