Complete PHP and MySQL Tutorial: Login, Logout, CRUD, and Export to PDF

This tutorial will guide you step-by-step to create a web application with PHP and MySQL that includes user authentication (login and logout), CRUD operations, and exporting data to PDF.
 

Prerequisites

  • Basic knowledge of PHP and MySQL.
  • XAMPP, WAMP, or any local server installed on your system.
  • A text editor like Visual Studio Code or Sublime Text.


Step 1: Set Up the Environment


Install XAMPP/WAMP:

Download and install XAMPP/WAMP to set up a local server.

Start Apache and MySQL:

Open the control panel and start Apache and MySQL.

Create a Database:

Go to http://localhost/phpmyadmin.

Create a database named tutorial_db.

Run the following SQL to create a users table and a records table:

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    password VARCHAR(255) NOT NULL
);

CREATE TABLE records (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(100) NOT NULL,
    description TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);


Install Composer (Optional):

Download and install Composer if you plan to use external libraries (e.g., for PDF generation).

 

Step 2: Create the File Structure

Create the following directory structure:

project/
|-- index.php
|-- login.php
|-- logout.php
|-- register.php
|-- crud/
|   |-- create.php
|   |-- read.php
|   |-- update.php
|   |-- delete.php
|-- export.php
|-- config/
    |-- database.php


 

Step 3: Database Configuration

Create config/database.php:

<?php
$host = 'localhost';
$db = 'tutorial_db';
$user = 'root';
$password = '';

try {
    $conn = new PDO("mysql:host=$host;dbname=$db", $user, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}
?>


 

Step 4: User Authentication (Login and Logout)

Register Users

Create register.php:

<?php
require 'config/database.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);

    $stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (:username, :password)");
    $stmt->execute(['username' => $username, 'password' => $password]);

    echo "Registration successful! <a href='login.php'>Login</a>";
}
?>

<form method="POST">
    <input type="text" name="username" placeholder="Username" required />
    <input type="password" name="password" placeholder="Password" required />
    <button type="submit">Register</button>
</form>


Login

Create login.php:

<?php
require 'config/database.php';
session_start();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];

    $stmt = $conn->prepare("SELECT * FROM users WHERE username = :username");
    $stmt->execute(['username' => $username]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['user_id'] = $user['id'];
        header('Location: index.php');
    } else {
        echo "Invalid username or password.";
    }
}
?>

<form method="POST">
    <input type="text" name="username" placeholder="Username" required />
    <input type="password" name="password" placeholder="Password" required />
    <button type="submit">Login</button>
</form>


Logout

Create logout.php:

<?php
session_start();
session_destroy();
header('Location: login.php');
?>


 

Step 5: CRUD Operations

Create a Record

Create crud/create.php:

<?php
require '../config/database.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = $_POST['title'];
    $description = $_POST['description'];

    $stmt = $conn->prepare("INSERT INTO records (title, description) VALUES (:title, :description)");
    $stmt->execute(['title' => $title, 'description' => $description]);

    header('Location: ../index.php');
}
?>

<form method="POST">
    <input type="text" name="title" placeholder="Title" required />
    <textarea name="description" placeholder="Description" required></textarea>
    <button type="submit">Create</button>
</form>


Read Records

Create crud/read.php:

<?php
require '../config/database.php';

$stmt = $conn->query("SELECT * FROM records");
$records = $stmt->fetchAll();

foreach ($records as $record) {
    echo "<h3>{$record['title']}</h3><p>{$record['description']}</p><hr>";
}
?>


 

Step 6: Export to PDF

Install Dompdf

Run:

composer require dompdf/dompdf

Create export.php

<?php
require 'vendor/autoload.php';
require 'config/database.php';

use Dompdf\Dompdf;

$stmt = $conn->query("SELECT * FROM records");
$records = $stmt->fetchAll();

$html = "<h1>Records</h1>";
foreach ($records as $record) {
    $html .= "<h3>{$record['title']}</h3><p>{$record['description']}</p><hr>";
}

dompdf = new Dompdf();
dompdf->loadHtml($html);
dompdf->setPaper('A4', 'portrait');
dompdf->render();
dompdf->stream("records.pdf", ["Attachment" => true]);
?>



This tutorial has shown how to build a complete PHP and MySQL application with authentication, CRUD, and PDF export functionality. Enhance this project by adding features like user roles, advanced search, or styling with CSS.  Hope this is helpful, and I apologize if there are any inaccuracies in the information provided.

Post a Comment for "Complete PHP and MySQL Tutorial: Login, Logout, CRUD, and Export to PDF"