In this post, we are going to learn about REST API implementation using PHP and MySQLi. A RESTful web service helps us to perform CRUD operations with MySQL database. In this post which is part of the REST API series, let us learn how to implement an easy and simple CRUD REST API using PHP and MySQLi for Create, Read, Update and Delete operations. The entire process will be handled with a help of core PHP not be using any framework as dependencies.
Most of the single page applications (or SPAs) enhancing very familiar and very quickly we see an increasing want to attach APIs for every process in it. Most organizations use the first step by building a simple and quick REST API. I write PHP script that makes a simple and quick REST API from your MySQL Database tables with full CRUD support.
Step 1: Database and Connect Details
Here we going to get contention with MySQL database using PHP with MySQLi contention property. Using this contention object we can process the CRUD process with REST API.
1 2 3 4 5 6 7 |
CREATE TABLE `li_ajax_post_load` ( `post_id` int(11) NOT NULL, `post_title` varchar(250) NOT NULL, `post_desc` text NOT NULL, `status` int(11) NOT NULL, PRIMARY KEY (`post_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; |
and connection object,
1 2 3 4 5 6 7 8 9 10 |
<?php //db details $db_host = 'localhost'; $db_user = 'root'; $db_pass = ''; $db_name = 'li_demo'; //connect and select db $con = mysqli_connect($db_host, $db_user, $db_pass, $db_name); ?> |
Step 2: Remove or Delete using REST API
The deletion record ID or keyword passed as a parameter and it helps to get and delete the particular data from a database, After this delete process, the REST API response as a JSON result data.
1 |
header('content-type:application/json'); |
and delete procedure help us to remove or delete data from database with the help of particular primary ID or Keyword,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
$actionName = $_POST["actionName"]; if($actionName == "deletePost"){ $postId = isset($_POST["postId"]) ? $_POST["postId"] : ''; if(!empty($postId)){ $query = "DELETE FROM li_ajax_post_load WHERE post_id=$postId"; $result = mysqli_query($con, $query); if($result){ $resultData = array('status' => true, 'message' => 'Post Deleted Successfully...'); }else{ $resultData = array('status' => false, 'message' => 'Can\'t able to delete a post details...'); } } else{ $resultData = array('status' => false, 'message' => 'Please enter post details...'); } echo json_encode($resultData); } |