Create PHP 8 CRUD REST API with MySQL & PHP PDO
If you aspire to hold a fundamental understanding of PHP frameworks, then you must check out our previous tutorial where we described How to Create a PHP Laravel 6 CRUD Web App with MySQL.
This tutorial is going to cover how to build a simple CRUD REST API in PHP and MySQL, Test PHP RESTful API with Postmen, and set up a PHP development environment on your local development system from scratch.
What is API (Application Programming Interface)?
API means Application Programming Interface, and It is a set of routines, protocols, and tools for creating software applications. An API interface makes communication possible between various software components.
In software development, API is a URL that handles the data for the web application through HTTP Requests GET, POST, UPDATE & DELETE, and manages the CRUD operations.
What is REST API?
Representational state transfer (REST) is a software architectural style that defines a set of constraints to be used for creating Web services. Web services that conform to the REST architectural style, called RESTful Web services, provide interoperability between computer systems on the Internet. RESTful Web services allow the requesting systems to access and manipulate textual representations of Web resources by using a uniform and predefined set of stateless operations. Other kinds of Web services, such as SOAP Web services, expose their own arbitrary sets of operations.
source: wikipedia
PHP 8 API Project File Structure
This is going to be the file structure of our PHP 8 REST API project, we created API, class, and config folders to store the API and MySQL database-related configuration files.
You can run your PHP project through MAMP or WAMP however we are using the command-line tool to start the PHP project.
Navigate to the directory where you have located your PHP project.
Once you are in the project folder then run the following command to start the PHP app.
The following output will be displayed on your terminal screen.
Check your project on the following URL: http://127.0.0.1:8080
MySQL Database Configuration
Before we get started we need to create a phpapidb
database, well this can be done through two methods either you can use the PhpMyAdmin, or you can do it by accessing the MySQL root user via the terminal or command-line tool to create the Database.
We have written a detailed article on Installing and Setting up MySQL in Mac’s Terminal app.
We are accessing the root user via command-line to create the database.
Create a new MySQL database.
Check the database.
Use the database.
Once you are done with the database creation, then you should run the SQL script to create the table.
Make sure what table you have created.
Populate data into the `Employee`
table.
If you are using PHP with MySQL 8.0+ you might get this error: The server requested authentication method unknown to the client
MySQL 8 uses auth_socket as a default plugin, so your applications require you to log in to your database using a password. You have to log in as root to mysql by using the following SQL script.
- You need to replace
'password'
it with your root password. - If your app is not logged in to your database with the root user, then replace the user in the above command with the user that your application is using.
Make Database Connection
The following code holds the MySQL database details such as db name, user name and password. It makes the database connection with PHP using the PDO.
The PHP Data Objects (PDO) extension specifies a lightweight, consistent interface for accessing databases in PHP. Every database driver that implements the PDO interface can expose database-specific features as regular extension functions. Note that you cannot perform any database functions using the PDO extension by itself; you must use a database-specific PDO driver to access a database server.
source – php.net
Create the config
folder inside the PHP API project, also create the database.php file and place the following code.
Create PHP Class
Now, we will create the PHP Class by the name of Employee. The PHP Classes are used to execute Object-Oriented Programming in PHP. PHP Classes encapsulate the values of the table for the Database. We will define the values that are stored in the variable form in the SQL table.
The SQL table properties are associated with the Connection class that is added via the constructor class.
Each object class contains the CRUD method that is being operated via the PHP functions to perform the CREATE, READ, UPDATE & DELETE operations for the defined table rows.
Create class/employees.php file and define the CRUD methods inside the Employee class.
The Employee class manages the CRUD operation
__construct()
— Makes the database connection ready.getEmployees()
— Get all records.getSingleEmployee()
— Get single records.createEmployee()
— Create a record.updateEmployee()
— Update record.deleteEmployee()
— Fetch single record.
Fetch MySQL Table Records using PHP REST API Endpoint
The following code retrieves all the records from the MySQL table. So create a read.php file in the api
folder and place the following code.
Let us test the PHP API Endpoint using Postman, open the Postman and use the following URL and click on the Send button to check the output.
Method | Endpoint |
---|---|
GET | http://localhost:8080/api/read.php |
Get Single Row from MySQL Database via PHP API
The following code fetches a single column from the MySQL database’s table. Create a single_read.php file in the api
folder and place the following code.
The SELECT statement is being used here to get the table’s column, in the following code, we are selecting the Employee values from the MySQL table.
Method | Endpoint |
---|---|
GET | localhost:8080/api/single_read.php/?id=2 |
Insert or Add Single Record in MySQL Table
In this step, we will create PHP REST API Endpoints to insert or add a single record in the MySQL table.
Create a create.php file in the api
folder and add the following code.
Method | Endpoint |
---|---|
POST | http://localhost:8080/api/create.php |
Edit/Update MySQL Table using PHP 8 API
This step explains to you how to Update or Edit the data for specific MySQL records. We can use the PHP 8 RESTful API to make the necessary update in the data that is stored in the MySQL database.
Create an update.php file in the api
folder and place the following code.
Method | Endpoint |
---|---|
POST | http://localhost:8080/api/update.php |
Remove/Delete Single Mysql Record using PHP API
Create delete.php file in api
folder in this file we will write the login to delete or remove the single employee record from MySQL data table using PHP 8 RESTful API. We will make the API call using the deletedEmployee()
method.
Method | Endpoint |
---|---|
DELETE | localhost:8080/api/delete.php |
Summary
So this was it, in this tutorial we have learned how to create a simple CRUD RESTful API with PHP 8 & MySQL 8, we also explored useful PHP methods such as htmlspecialchars(), bindParam(), execute(), PHP PDO and json_encode().