How to Create a PHP 8 & MySQL CRUD RESTful API
In this tutorial, we will guide you through creating a simple PHP 8 CRUD RESTful API with MySQL, covering how to Create, Read, Update, and Delete records from a MySQL database. This tutorial assumes you have a basic understanding of PHP and MySQL.
What is an API?
An API (Application Programming Interface) is a set of protocols and tools that allows software applications to communicate with each other. APIs define the methods and data formats that applications use to interact.
What is a REST API?
A REST API (Representational State Transfer) is a type of web service that follows the REST architectural style. It allows you to interact with resources (like database records) through standard HTTP methods such as GET, POST, PUT, and DELETE. A RESTful API is stateless, meaning each request from the client contains all the information the server needs to process it.
Setting Up the Project
PHP Project File Structure
Create the following folder structure for your PHP project:
You can use MAMP or WAMP to set up the local PHP development environment, but we'll use the command line to run the PHP project.
Run the following command to start your PHP app:
MySQL Database Setup
Before we start, we need to set up the MySQL database. You can do this using PhpMyAdmin or directly through the command line.
-
Create a new database:
-
Create a table for storing employee data:
-
Insert sample data into the Employee table:
Building the API
Database Connection
To connect PHP to the MySQL database, we'll use PDO (PHP Data Objects). In the /config/database.php
file, we define the database connection:
Create PHP Class for CRUD Operations
The Employee
class will handle all CRUD operations. Here’s an example of how you can structure it:
API Endpoints
Now, create the PHP files to implement the CRUD operations as API endpoints.
-
Create (POST request):
create.php
-
Read (GET request):
read.php
-
Update (POST request):
update.php
-
Delete (POST request):
delete.php
Each file will correspond to a specific action like creating a new record or updating an existing one. You can refer to the previous tutorial for the complete code for each endpoint.
Testing the API
You can test the PHP API using Postman or any HTTP client. Here are the endpoints to test the operations:
-
Create a new employee (POST):
http://localhost:8080/api/create.php
-
Get all employees (GET):
http://localhost:8080/api/read.php
-
Get a single employee (GET):
http://localhost:8080/api/single_read.php?id=2
-
Update an employee (POST):
http://localhost:8080/api/update.php
-
Delete an employee (POST):
http://localhost:8080/api/delete.php
Conclusion
This tutorial covered how to create a simple CRUD API using PHP 8 and **MySQL