The student will be able do the following tasks after completing the tutorial.
- Understand the fundamentals of user authentication.
- Learn how to store and retrieve data from MySQL dynamically.
- Gain insights into error handling and security best practices.
- Build a simple CRUD application (blog or task manager).
User Authentication: Login and Registration System
- Why authentication is necessary (security, personalized user experience).
- Steps in a basic authentication system:
- Registration (adding user data to the database).
- Login (verifying user credentials).
- Session management (keeping users logged in).
Database Setup:
Create a users table:
CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL UNIQUE, password VARCHAR(255) NOT NULL );
Explain password hashing using password_hash() and password_verify() in PHP for security.
Hands-On Code:
Registration Form (register.php):
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { $username = htmlspecialchars($_POST['username']); $password = password_hash($_POST['password'], PASSWORD_DEFAULT); $conn = new mysqli("localhost", "root", "", "mydatabase"); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)"); $stmt->bind_param("ss", $username, $password); if ($stmt->execute()) { echo "Registration successful!"; } else { echo "Error: " . $stmt->error; } $stmt->close(); $conn->close(); } ?> <form method="POST"> Username: <input type="text" name="username" required><br> Password: <input type="password" name="password" required><br> <button type="submit">Register</button> </form>
Login Form (login.php):
<?php session_start(); if ($_SERVER["REQUEST_METHOD"] == "POST") { $username = htmlspecialchars($_POST['username']); $password = $_POST['password']; $conn = new mysqli("localhost", "root", "", "mydatabase"); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $stmt = $conn->prepare("SELECT password FROM users WHERE username = ?"); $stmt->bind_param("s", $username); $stmt->execute(); $stmt->bind_result($hashed_password); if ($stmt->fetch() && password_verify($password, $hashed_password)) { $_SESSION['username'] = $username; echo "Login successful!"; } else { echo "Invalid credentials!"; } $stmt->close(); $conn->close(); } ?> <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>
Storing and Retrieving Data Dynamically from MySQL
CRUD operations:
- Create: Insert data into the database.
- Read: Retrieve data using SELECT queries.
- Update: Modify existing records.
- Delete: Remove records.
Hands-On Code:
Creating Data (Add a Task):
<?php $task = htmlspecialchars($_POST['task']); $conn = new mysqli("localhost", "root", "", "mydatabase"); $stmt = $conn->prepare("INSERT INTO tasks (task) VALUES (?)"); $stmt->bind_param("s", $task); $stmt->execute(); $stmt->close(); $conn->close(); ?> <form method="POST"> Task: <input type="text" name="task" required> <button type="submit">Add Task</button> </form>
Reading Data (Display Tasks):
<?php $conn = new mysqli("localhost", "root", "", "mydatabase"); $result = $conn->query("SELECT * FROM tasks"); while ($row = $result->fetch_assoc()) { echo $row['task'] . "<br>"; } $conn->close(); ?>
Error Handling and Security Best Practices
Error Handling:
- Use try and catch blocks for error management in database operations.
- Log errors instead of displaying them to users.
Security Best Practices:
- Sanitize user input using htmlspecialchars() or mysqli_real_escape_string().
- Always use prepared statements to prevent SQL injection.
- Hash sensitive data like passwords with password_hash().
- Avoid storing sensitive credentials (e.g., database passwords) in code—use environment variables.
Lab Exercise: Build a Simple CRUD Application
Create a task manager application where users can add, view, edit, and delete tasks.