Posted in

Building a Simple PHP CRUD Application with Navigation Menu

Introduction

CRUD (Create, Read, Update, Delete) operations are the foundation of most web applications. In this post, I will walk you through building a basic PHP CRUD application using PDO (PHP Data Objects) and MySQL. This application features a simple navigation menu, making it easy to switch between CRUD functions.

Why Use PDO for Database Operations?

PDO provides a secure and flexible way to interact with databases in PHP. It helps prevent SQL injection and supports multiple database systems, including MySQL, PostgreSQL, and SQLite.

Project Overview

Our application will allow users to manage a list of products with basic CRUD functionality:

  • Create: Add new products.
  • Read: Display a list of all products.
  • Update: Edit product details.
  • Delete: Remove products from the database.

Features:

✅ Uses PDO for secure database interaction. ✅ Includes a navigation menu for easy access to CRUD operations. ✅ Compatible with Laragon, LAMP, or PHP built-in server. ✅ Simple and user-friendly UI.

Step-by-Step Guide to Building the CRUD Application

Step 1: Setting Up the Database

First, create a database and a products table in MySQL:

CREATE DATABASE test_db;
USE test_db;

CREATE TABLE products (
    id INT AUTO_INCREMENT PRIMARY KEY,
    product_name VARCHAR(255) NOT NULL,
    price DECIMAL(10,2) NOT NULL
);

INSERT INTO products (product_name, price) VALUES
('Laptop', 1200.50),
('Smartphone', 699.99),
('Tablet', 399.99);

Step 2: Configuring the Database Connection (db.php)

<?php
$dsn = 'mysql:host=localhost;dbname=test_db;charset=utf8mb4';
$username = 'root';
$password = '';
$options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
$pdo = new PDO($dsn, $username, $password, $options);
?>

Step 3: Creating the Navigation Menu (menu.php)

<nav>
    <a href="index.php">Home</a> |
    <a href="create.php">Add Product</a>
</nav>
<hr>

Step 4: Implementing CRUD Functionality

1. List Products (index.php)

<?php
include 'db.php';
include 'menu.php';
$products = $pdo->query("SELECT * FROM products")->fetchAll(PDO::FETCH_ASSOC);
?>
<table>
    <tr><th>ID</th><th>Product Name</th><th>Price</th><th>Actions</th></tr>
    <?php foreach ($products as $product): ?>
    <tr>
        <td><?= $product['id'] ?></td>
        <td><?= $product['product_name'] ?></td>
        <td><?= $product['price'] ?></td>
        <td>
            <a href="update.php?id=<?= $product['id'] ?>">Edit</a> |
            <a href="delete.php?id=<?= $product['id'] ?>" onclick="return confirm('Delete this product?')">Delete</a>
        </td>
    </tr>
    <?php endforeach; ?>
</table>

2. Add a New Product (create.php)

<?php
include 'db.php';
include 'menu.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $stmt = $pdo->prepare("INSERT INTO products (product_name, price) VALUES (?, ?)");
    $stmt->execute([$_POST['product_name'], $_POST['price']]);
    header("Location: index.php");
    exit;
}
?>
<form method="POST">
    Product Name: <input type="text" name="product_name" required><br>
    Price: <input type="number" name="price" step="0.01" required><br>
    <button type="submit">Add</button>
</form>

3. Update a Product (update.php)

<?php
include 'db.php';
include 'menu.php';
$id = $_GET['id'];
$product = $pdo->prepare("SELECT * FROM products WHERE id = ?");
$product->execute([$id]);
$product = $product->fetch(PDO::FETCH_ASSOC);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $stmt = $pdo->prepare("UPDATE products SET product_name = ?, price = ? WHERE id = ?");
    $stmt->execute([$_POST['product_name'], $_POST['price'], $id]);
    header("Location: index.php");
    exit;
}
?>
<form method="POST">
    Product Name: <input type="text" name="product_name" value="<?= $product['product_name'] ?>" required><br>
    Price: <input type="number" name="price" value="<?= $product['price'] ?>" step="0.01" required><br>
    <button type="submit">Update</button>
</form>

4. Delete a Product (delete.php)

<?php
include 'db.php';
$id = $_GET['id'];
$stmt = $pdo->prepare("DELETE FROM products WHERE id = ?");
$stmt->execute([$id]);
header("Location: index.php");
exit;
?>

Step 5: Running the Application

Using PHP Built-in Server

php -S localhost:8000

Open your browser and go to:

http://localhost:8000/index.php

Using Laragon or LAMP Server

  • Laragon:
    • Place the project in C:\laragon\www\
    • Start Laragon and go to: http://localhost/php-crud-menu/index.php
  • LAMP (Linux, Apache, MySQL, PHP):
    • Move the project to /var/www/html/
    • Restart Apache: sudo systemctl restart apache2
    • Open in browser: http://localhost/php-crud-menu/index.php

Conclusion

Congratulations! 🎉 You have successfully built a simple PHP CRUD application with a navigation menu. This project serves as a solid foundation for more complex applications.

If you found this guide helpful, share it with others! 🚀

Additional References

You may refer to these repositories for more examples:


🔗 Stay Connected 📌 Follow for more PHP tutorials and projects!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.