• PHP
  • MySQL
  • Demos
  • HTML
  • CSS
  • jQuery
  • Framework
  • Social
  • Request Tutorial
PHP Lift
  • Home
  • Demos
  • PHP Jobs
  • Advertisement
PHP Lift
  • PHP
  • MySQL
  • Demos
  • HTML
  • CSS
  • jQuery
  • Framework
  • Social
  • Request Tutorial
  • Follow
    • Facebook
    • Twitter
    • Google+
    • Youtube
    • RSS
Simple PHP REST API with Slim, PHP & MySQL
Home
MySQL

Simple PHP REST API with Slim, PHP & MySQL

August 27th, 2020 Huzoor Bux API, MySQL, PHP 0 comments

Facebook Twitter Google+ LinkedIn Pinterest

I have received many requests from readers and after lots of searching I found out a lightweight framework to create PHP RESTful API Tutorial. There are a number of frameworks available and the one I chose is SLIM (it is a micro framework that helps you efficiently write powerful web services). This tutorial gives you complete examples of creating full Restful API using multiple HTTP methods like GET, POST, PUT, and DELETE. You would get the output in JSON and create a user data for all options, download code available.

DEMO
DOWNLOAD CODE

HTTP methods:

GET: Used to retrieve and search for data.

POST: Used to insert data.

PUT: Used to update data.

DELETE: Used to delete data.

Add below .htaccess file in your API folder http://localhost/api

RewriteEngine On

RewriteBase /api # if hosting api files on root use only /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]

Database design and table:
database name => phpgang
table name => restAPI
column names => id, name, email, IP, date
db.sql
Database file runs in your MySQL to create a database and add data in the table.

-- 
-- Table structure for table `restAPI`
-- 

CREATE TABLE `restAPI` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(240) NOT NULL,
  `email` varchar(240) NOT NULL,
  `password` varchar(240) NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `ip` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
);

Database configuration

Edit database name, user and password as per your configuration

function getConnection() {
    try {
        $db_username = "DATABASE_NAME";
        $db_password = "********";
        $conn = new PDO('mysql:host=localhost;dbname=root', $db_username, $db_password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
    return $conn;
}

Used PDO connection you can use as per your ease and I have added this function in the same methods file you can also manage them as per your projects.

Implement API

We have created 6 API methods

  1. getUsers
  2. getUser
  3. findByName
  4. addUser
  5. updateUser
  6. deleteUser

Define HTTP routes:

$app->get('/users', 'getUsers'); // Using Get HTTP Method and process getUsers function
$app->get('/users/:id',    'getUser'); // Using Get HTTP Method and process getUser function
$app->get('/users/search/:query', 'findByName'); // Using Get HTTP Method and process findByName function
$app->post('/users', 'addUser'); // Using Post HTTP Method and process addUser function
$app->put('/users/:id', 'updateUser'); // Using Put HTTP Method and process updateUser function
$app->delete('/users/:id',    'deleteUser'); // Using Delete HTTP Method and process deleteUser function
$app->run();

These all routes call an individual function as defined above and in the last $app->run(); used to run Slim application.

let’s see functions:

1. getUsers: $app->get(‘/users’, ‘getUsers’);

function getUsers() {
    $sql_query = "select `name`,`email`,`date`,`ip` FROM restAPI ORDER BY name";
    try {
        $dbCon = getConnection();
        $stmt   = $dbCon->query($sql_query);
        $users  = $stmt->fetchAll(PDO::FETCH_OBJ);
        $dbCon = null;
        echo '{"users": ' . json_encode($users) . '}';
    }
    catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }    
}

This function simply return all users information as you can see in this query, to call this API use this URL http://localhost/api/users this is it for your first API using get route.

2. getUser: $app->get(‘/users/:id’,    ‘getUser’); In this route we are sending id.

function getUser($id) {
    $sql = "SELECT `name`,`email`,`date`,`ip` FROM restAPI WHERE id=:id";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);  
        $stmt->bindParam("id", $id);
        $stmt->execute();
        $user = $stmt->fetchObject();  
        $dbCon = null;
        echo json_encode($user); 
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

This function checks the record of the given id and return if found anything,  to call this API use this URL http://localhost/api/users/1.

3. findByName: $app->get(‘/users/search/:query’, ‘findByName’); Route is used to search record with extra parameter and a search query with simple get method.

function findByName($query) {
    $sql = "SELECT * FROM restAPI WHERE UPPER(name) LIKE :query ORDER BY name";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);
        $query = "%".$query."%";
        $stmt->bindParam("query", $query);
        $stmt->execute();
        $users = $stmt->fetchAll(PDO::FETCH_OBJ);
        $dbCon = null;
        echo '{"user": ' . json_encode($users) . '}';
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

This function search in the database for your given query, to call this API use this URL http://localhost/api/users/search/phpgang.

create PHP REST API

4. addUser: $app->post(‘/users’, ‘addUser’); API used to add new record and accept post.

function addUser() {
    global $app;
    $req = $app->request(); // Getting parameter with names
    $paramName = $req->params('name'); // Getting parameter with names
    $paramEmail = $req->params('email'); // Getting parameter with names

    $sql = "INSERT INTO restAPI (`name`,`email`,`ip`) VALUES (:name, :email, :ip)";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);  
        $stmt->bindParam("name", $paramName);
        $stmt->bindParam("email", $paramEmail);
        $stmt->bindParam("ip", $_SERVER['REMOTE_ADDR']);
        $stmt->execute();
        $user->id = $dbCon->lastInsertId();
        $dbCon = null;
        echo json_encode($user); 
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

This API accepts post request and insert submitted data in your database as we received parameters in starting of that function. To call this API I have used cURL, you can use jQuery or any other technique.

<?php
if($_POST){
    echo post_to_url("http://localhost/users", $_POST);
} else{
 ?>
ADD RECORD.
<form action="" method="post">
<input type="text" name="name" placeholder="Name" /><br>
<input type="text" name="email" placeholder="Email" /><br>
<input type="hidden" name="_METHOD" value="POST" />
<input type="submit" value="A D D" />
</form>
<?php 
}
?>

This form will be submitted to your action file and there is a curl and that curl will post data as I have used a hidden input of _METHOD with POST value this is because some times your cURL don’t Post data to API (faced this so used this for the post as well) and Slim give us this functionality to method override and as our modern browsers do not have native support to PUT and delete so we have to use method overriding like below.

PHP RESTful API

<input type="hidden" name="_METHOD" value="POST" /> <!-- POST data -->
<input type="hidden" name="_METHOD" value="PUT" /> <!-- PUT data -->
<input type="hidden" name="_METHOD" value="DELETE" /> <!-- DELETE data -->

cURL function to post data:

function post_curl($_url, $_data) {
   $mfields = '';
   foreach($_data as $key => $val) { 
      $mfields .= $key . '=' . $val . '&'; 
   }
   rtrim($mfields, '&');
   $pst = curl_init();

   curl_setopt($pst, CURLOPT_URL, $_url);
   curl_setopt($pst, CURLOPT_POST, count($_data));
   curl_setopt($pst, CURLOPT_POSTFIELDS, $mfields);
   curl_setopt($pst, CURLOPT_RETURNTRANSFER, 1);

   $res = curl_exec($pst);

   curl_close($pst);
   return $res;
}

5. updateUser: $app->put(‘/users/:id’, ‘updateUser’); This route accept put HTTP method.

function updateUser($id) {
    global $app;
    $req = $app->request();
    $paramName = $req->params('name');
    $paramEmail = $req->params('email');

    $sql = "UPDATE restAPI SET name=:name, email=:email WHERE id=:id";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);  
        $stmt->bindParam("name", $paramName);
        $stmt->bindParam("email", $paramEmail);
        $stmt->bindParam("id", $id);
        $stmt->execute();
        $status = false;
        if($stmt->rowCount() > 0)
           $status = true;
        $dbCon = null;
        echo json_encode($status); 
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

This API function updates your data by id, to call this API we need to again use cURL and HTML form.

<?php
if($_POST){
        echo post_to_url("http://localhost/users/".$_POST['id'], $_POST); // add id after last slash which you want to edit.
} else{
UPDATE RECORD.
<br>
<form action="" method="post">
<input type="text" name="id" placeholder="Id to update" /><br>
<input type="text" name="name" placeholder="Name" /><br>
<input type="text" name="email" placeholder="Email" /><br>
<input type="hidden" name="_METHOD" value="PUT" />
<input type="submit" value="U P D A T E" />
</form>
<?php 
}
?>

6. deleteUser: $app->delete(‘/users/:id’,    ‘deleteUser’); Route used to delete specific ID.

function deleteUser($id) {
    $sql = "DELETE FROM restAPI WHERE id=:id";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);  
        $stmt->bindParam("id", $id);
        $stmt->execute();
        $status = false;
        if($stmt->rowCount() > 0)
           $status = true;
        $dbCon = null;
        echo json_encode($status);
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

This API function accepts HTTP delete request and to send HTTP delete method we have to used method overriding using our hidden field named _METHOD and value will be DELETE form and cURL code given below.

<?php
if($_POST){
        echo post_to_url("http://localhost/users/".$_POST['id'], $_POST);
} else{
 ?>
DELETE RECORD.
<br>
<form action="" method="post">
<input type="text" name="id" placeholder="Id to delete" /><br>
<input type="hidden" name="_METHOD" value="DELETE" />
<input type="submit" value="D E L E T E" />
</form>
 <?php 
}
?>

That’s all for our one of the biggest tutorial for RESTful API, I hope you like this tutorial and please don’t forget to give us your feedback and any issue you have faced in this tutorial please do comment we try our level best to solve your problems.

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)

Related

  • Tags
  • api
  • How to
  • MYSQL
  • PHP and MySQL
  • RESTful API
  • RESTful Webservice
  • Slim framework
  • Webservice with Slim
Facebook Twitter Google+ LinkedIn Pinterest
Next article Create HTML5 Fullscreen Static Video Background Using CSS
Previous article PHP Contact Form with Google reCAPTCHA V3

Huzoor Bux

I am a PHP Developer

Related Posts

Stripe Payment Gateway Charge Credit Card with PHP API
February 15th, 2021

Stripe Payment Gateway Charge Credit Card with PHP

6 Reasons Laravel is the Top PHP Framework in the Web Development Industry Framework
February 1st, 2021

6 Reasons Laravel is the Top PHP Framework in the Web Development Industry

12 Reasons to Choose PHP for Developing Website Guide
November 17th, 2020

12 Reasons to Choose PHP for Developing Website

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Advertisement
Recent Posts
  • Stripe Payment Gateway Charge Credit Card with PHP
  • How to building responsive WordPress theme using Bootstrap
  • 6 Reasons Laravel is the Top PHP Framework in the Web Development Industry
  • 9 Best Programming languages you should learn in 2021
  • 12 Reasons to Choose PHP for Developing Website
Categories
  • API
  • Bootstrap
  • CSS
  • CSS 3
  • Designing
  • Framework
  • Guide
  • HTML
  • HTML 5
  • JavaScript
  • jQuery
  • MySQL
  • Node.js
  • oAuth
  • Payment
  • PHP
  • Python
  • Social
  • Tips
  • WordPress
Weekly Tags
  • PHP
  • api
  • How to
  • PHP Basics
  • Programming Habits
  • HTML5
  • PHP framework
  • Download
  • laravel
  • css
  • About
  • Privacy Policy
  • Back to top
© PHPLift 2020. All rights reserved.