Create a REST API Using PHP & MySQL
I am writing this tutorial to show you how to create a RESTful web-service with PHP 7 & MySQL 8 in a very short time. You can think of this post as a primer. I’ll try to explain the core topics as much as possible while avoiding generic things.
Please note that mysql extension for PHP has been completely discontinued in PHP 7. That is why you can only use mysqli extension. My entire API is based on mysqli extension only.
This tutorial assumes that you know: –
- What an API & REST means.
- What is a REST client.
- What is a RESTful service.
- How to set up a web-server. I am using
Apache/2.4.34. - How to install the necessary Apache modules.
Application description
It is a very simple To-Do app that is completely based on REST architecture & doesn’t have any GUI. You create or retrieve your To-Do’s using the REST API only.
Newly created To-Do’s are stored in a MySQL database.
I have kept this API extremely simple on purpose. My sole aim here is to get you (& me) started with writing an API & interacting with it. I have skipped database security intentionally & will modify the code later. This tutorial is all about knowing how APIs are created & how you can see REST in action.
Requirements
- PHP 7
- MySQL 8
- REST Client such as Postman.
cURLor your favorite browser can also be used.
I am using PHP 7.1.23, MySQL 8.0.16 & Postman for this tutorial. You can use any REST client of your choice. I like Postman better as it makes it very easy & convenient to work with REST.
Steps to perform
1. Create a Database & table
Create a database & table in MySQL to store the data.
CREATE DATABASE IF NOT EXISTS `my_to_do_db`; USE my_to_do_db -- -- Table structure for table `my_to_do_tb` -- CREATE TABLE IF NOT EXISTS `my_to_do_tb` ( `task` text NOT NULL, `date` text NOT NULL, `priority` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1 ;
2. Create config.php script
This PHP script will store database connection-related information. I have kept database credentials in a separate file to-do.ini to avoid hard-coding the password. This file resides in a directory one level above the DocumentRoot. You can put this file anywhere. Just make sure that you refer to the correct location in config.php script.
config.php script references to-do.ini file.
username=root password=ZahidHossain1234001 dbhost=localhost db=my_to_do_db
config.php
<?php
$config = parse_ini_file('/Users/admin/Sites/to-do.ini');
$conn = mysqli_connect($config['dbhost'], $config['username'], $config['password']);
mysqli_select_db($conn, $config['db']);