Lesson :- 9 CRUD API in PHP – Complete Notes with Theory + Code

 

🌐 CRUD API in PHP – Complete Guide



🧠 What is a CRUD API?

CRUD = Create, Read, Update, Delete

An API (Application Programming Interface) allows communication between applications. A CRUD API lets you perform basic database operations via HTTP methods:

Operation HTTP Method Endpoint
Create POST /create.php
Read GET /read.php
Update PUT /update.php
Delete DELETE /delete.php

📁 Folder Structure

crud-api/
│
├── db.php           ← Database connection
├── create.php       ← Insert record
├── read.php         ← Fetch records
├── update.php       ← Update record
├── delete.php       ← Delete record
└── .htaccess        ← (Optional) Clean URLs
  

🏗️ Step-by-Step Setup

🔹 1. Create Database & Table

CREATE DATABASE crud_db;

USE crud_db;

CREATE TABLE students (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100),
    course VARCHAR(100)
);
  

🔹 2. db.php – Database Connection

<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbname = "crud_db";

$conn = mysqli_connect($host, $user, $pass, $dbname);

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

🔹 3. create.php – Insert Record

<?php
include 'db.php';

$data = json_decode(file_get_contents("php://input"));

$name = $data->name;
$email = $data->email;
$course = $data->course;

$sql = "INSERT INTO students (name, email, course) VALUES ('$name', '$email', '$course')";
if (mysqli_query($conn, $sql)) {
    echo json_encode(["message" => "Record inserted successfully!"]);
} else {
    echo json_encode(["error" => "Insert failed!"]);
}
?>
  

🔹 4. read.php – Fetch All Records

<?php
include 'db.php';

$sql = "SELECT * FROM students";
$result = mysqli_query($conn, $sql);

$students = [];

while ($row = mysqli_fetch_assoc($result)) {
    $students[] = $row;
}

echo json_encode($students);
?>
  

🔹 5. update.php – Update Record

<?php
include 'db.php';

$data = json_decode(file_get_contents("php://input"));

$id = $data->id;
$name = $data->name;
$email = $data->email;
$course = $data->course;

$sql = "UPDATE students SET name='$name', email='$email', course='$course' WHERE id=$id";
if (mysqli_query($conn, $sql)) {
    echo json_encode(["message" => "Record updated successfully!"]);
} else {
    echo json_encode(["error" => "Update failed!"]);
}
?>
  

🔹 6. delete.php – Delete Record

<?php
include 'db.php';

$data = json_decode(file_get_contents("php://input"));
$id = $data->id;

$sql = "DELETE FROM students WHERE id=$id";
if (mysqli_query($conn, $sql)) {
    echo json_encode(["message" => "Record deleted!"]);
} else {
    echo json_encode(["error" => "Delete failed!"]);
}
?>
  

🌐 .htaccess (Optional for Pretty URLs)

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ $1.php [NC,L]
  

🧪 How to Test

  • Use Postman or JavaScript fetch()
  • POST /create.php with body:
    {
      "name": "John Doe",
      "email": "john@example.com",
      "course": "PHP"
    }
          
  • GET /read.php to fetch records
  • PUT /update.php with updated data
  • DELETE /delete.php with {"id": 1}

✅ Summary

✔ Built a RESTful API using PHP + MySQL

✔ Ready to integrate with frontend apps (React, Vue, mobile)

✔ Ideal for projects, CMS, blog systems, portfolios

Post a Comment

0 Comments