Introduction: In the ever-evolving landscape of web development, creating a RESTful API is a crucial skill. This blog post will guide you through the process of building a simple REST API using PHP and MySQL, focusing on the same student dataset introduced in the previous post. We’ll cover the basic operations: Create, Read, Update, and Delete (CRUD).
Prerequisites:
Ensure you have:
- A web server (like Apache or Nginx) with PHP installed.
- A MySQL database with the “students” table (as defined in the previous blog post).
Setting Up the Project Structure:
Create a project folder and organize it as follows:
/rest-api-project
/config
database.php
/includes
student.php
index.php
Connecting to the Database:
Start by creating a database.php
file in the config
folder:
<?php
$host = 'your_database_host';
$dbname = 'your_database_name';
$username = 'your_username';
$password = 'your_password';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
?>
Creating CRUD Operations:
Define the CRUD operations in the student.php
file within the includes
folder:
<?php
class Student {
private $conn;
private $table = 'students';
public function __construct($db) {
$this->conn = $db;
}
// Read all students
public function read() {
$query = 'SELECT * FROM ' . $this->table;
$stmt = $this->conn->prepare($query);
$stmt->execute();
return $stmt;
}
// Read single student
public function readSingle($id) {
$query = 'SELECT * FROM ' . $this->table . ' WHERE id = ?';
$stmt = $this->conn->prepare($query);
$stmt->execute([$id]);
return $stmt;
}
// Create student
public function create($name, $age, $grade) {
$query = 'INSERT INTO ' . $this->table . ' (name, age, grade) VALUES (?, ?, ?)';
$stmt = $this->conn->prepare($query);
$stmt->execute([$name, $age, $grade]);
return $stmt;
}
// Update student
public function update($id, $newAge) {
$query = 'UPDATE ' . $this->table . ' SET age = ? WHERE id = ?';
$stmt = $this->conn->prepare($query);
$stmt->execute([$newAge, $id]);
return $stmt;
}
// Delete student
public function delete($id) {
$query = 'DELETE FROM ' . $this->table . ' WHERE id = ?';
$stmt = $this->conn->prepare($query);
$stmt->execute([$id]);
return $stmt;
}
}
?>
Implementing the API Endpoints:
Now, in the index.php
file, handle incoming HTTP requests and call the appropriate methods:
<?php
header('Content-Type: application/json');
include_once 'config/database.php';
include_once 'includes/student.php';
$database = new Database();
$db = $database->getConnection();
$student = new Student($db);
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
// Read all students
$stmt = $student->read();
echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Create student
$data = json_decode(file_get_contents('php://input'));
$stmt = $student->create($data->name, $data->age, $data->grade);
echo json_encode(['message' => 'Student created']);
} elseif ($_SERVER['REQUEST_METHOD'] === 'PUT') {
// Update student
$data = json_decode(file_get_contents('php://input'));
$stmt = $student->update($data->id, $data->newAge);
echo json_encode(['message' => 'Student updated']);
} elseif ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
// Delete student
$data = json_decode(file_get_contents('php://input'));
$stmt = $student->delete($data->id);
echo json_encode(['message' => 'Student deleted']);
} else {
http_response_code(405); // Method Not Allowed
echo json_encode(['message' => 'Method not allowed']);
}
?>
Conclusion: Congratulations! You have successfully created a simple REST API using PHP and MySQL. REST APIs play a crucial role in modern web development, enabling seamless communication between different systems.