Building a Simple CRUD Application with PHP and MySQL

Introduction

A CRUD (Create, Read, Update, Delete) application is the foundation of most web applications. In this tutorial, we’ll build a simple CRUD system using PHP and MySQL.

Step 1: Create a Database

Open MySQL and create a database:

sqlCopy codeCREATE DATABASE my_database;
USE my_database;

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255),
    email VARCHAR(255)
);

Step 2: Connect PHP to MySQL

Create a file db.php:

phpCopy code<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbname = "my_database";

$conn = new mysqli($host, $user, $pass, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>

Step 3: Create a Form to Insert Data

phpCopy code<form method="POST" action="insert.php">
    <input type="text" name="name" placeholder="Enter Name">
    <input type="email" name="email" placeholder="Enter Email">
    <button type="submit">Add User</button>
</form>

Step 4: Insert Data into Database

Create insert.php:

phpCopy code<?php
include 'db.php';

$name = $_POST['name'];
$email = $_POST['email'];

$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
$conn->query($sql);

header("Location: index.php");
?>

Step 5: Display Data (Read Operation)

Create index.php:

phpCopy code<?php
include 'db.php';
$result = $conn->query("SELECT * FROM users");

while ($row = $result->fetch_assoc()) {
    echo "<p>{$row['name']} - {$row['email']} <a href='delete.php?id={$row['id']}'>Delete</a></p>";
}
?>

Step 6: Delete a User

Create delete.php:

phpCopy code<?php
include 'db.php';
$id = $_GET['id'];
$conn->query("DELETE FROM users WHERE id=$id");
header("Location: index.php");
?>

Conclusion

Congratulations! You’ve built a simple CRUD application in PHP and MySQL. You can expand it by adding an Update feature and styling it with CSS.

Leave a Comment

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

Scroll to Top