Skip to main content

REST API in PHP

Step 1. Create a table in database mysql with below script.


          CREATE TABLE `facts` (
                `Id` int(11) NOT NULL,
                 `title` varchar(512) NOT NULL,
                 `myth` varchar(512) NOT NULL,
                 `fact` varchar(512) NOT NULL
           ) ENGINE=InnoDB DEFAULT CHARSET=latin1;


Step 2. Create a folder in xampp/htdocs/testRestAPI
      Here we need to create 2 main files
1.    Database.php
2.    GetAllFacts.php
In database.php we will write the code for connecting database to php. As shown below.

Database.php


<?php
$servername = "localhost";
$username = "manoj";//specify your username
$password = "root";//specify your password

try {
    $conn = new PDO("mysql:host=$servername;dbname=kamasutra", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //echo "Connected successfully";
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }
?>


In the above code we are creating connection with php. And this database file is used in another page there we are getting all the facts and myths about something that saved in database.
Here is second file that contains code to get and display data retrieve from database.

GetAllFacts.php

<?php 
   /*

   * Following the code will get list of values from code

   * A product is identified by product id (pid)

   */ 
 
   // array for JSON response 
 
   $response = array(); 
 
   // include db connect class 
 
   include 'database.php';  
 
   // connecting to db 
 
      // get a product from products table 
           
            $statement = $conn->prepare("select * from facts");
            $statement->execute();
            $result = $statement->fetchAll(PDO::FETCH_ASSOC);
       
      if (!empty($result)) { 
       
         // check for empty result 
         $count = sizeof($result);
         if ($count > 0) { 
 
            $facts = array(); 
            // success 
 
            $response["success"] = 1; 
 
            // user node 
 
            $response["facts"] = array(); 
 
            array_push($response["facts"], $result); 
 
            // echoing JSON response 
 
            echo json_encode($response); 
 
         } else { 
 
            // no product found 
 
            $response["success"] = 0; 
 
            $response["message"] = "No product found"; 
 
            // echo no users JSON 
 
            echo json_encode($response); 
 
         } 
 
      } else { 
 
         // no product found 
 
         $response["success"] = 0; 
 
         $response["message"] = "No product found"; 
 
         // echo no users JSON 
 
         echo json_encode($response); 
 
      } 
 
   //} 
 
?> 

The major difference between API and web application is that Web application will always return data from file in html, where as in API we have to return data in xml or JSON.
Nowdays we are using JSON much more as compare to xml in the above code we are returning values in JSON format. The output of the above code is .

Output: 

   "success":1,
   "facts":[ 
      [ 
         { 
            "Id":"1",
            "title":"title1",
            "myth":"myth1",
            "fact":"fact1"
         },
         { 
            "Id":"2",
            "title":"title2",
            "myth":"myth2",
            "fact":"fact2"
         }
      ]
   ]
}


To get full code and in case of any issue please comment below and subscribe, like our page for being in touch with us.

Comments

Popular posts from this blog

Creating JDBC Connection in web application

There are following are six steps involved in creating a JDBC application − ·         Import Require packages:  we need to import JDBC packages that are Requires while creating connection with mysql. JDBC classes needed for database connectoin. Most often, using  import java.sql.*  will suffice. ·         Register the JDBC driver:  Driver manager class will attempt to load driver referenced in the jdbc.drivers. This makes User to customize the JDBC drivers Used by their application. ·          Open a connection :  it need the  DriverManager.getConnection()  method to create a Connection object, which represents a physical connection with the database. ·         Execute a query: For executing a query we will call execute methods from different statements 1.   Execute : Return true if the fir...

LOGIN AND SIGN UP USING BOOTSTRAP

WHAT IS BOOTSTRAP? ·         Bootstrap is a sleek, intuitive, and powerful, mobile first front-end framework for faster and easier web development. It uses HTML, CSS and Javascript. HISTORY:- ·          Bootstrap was developed by  Mark Otto  and  Jacob Thornton  at  Twitter . It was released as an open source product in August 2011 on GitHub. WHY USE BOOTSTRAP? ·          Mobile first approach  − Bootstrap 3, framework consists of Mobile first styles throughout the entire library instead them of in separate files. Browser Support  − It is supported by all popular browsers. ·          Easy to get started  − With just the knowledge of HTML and CSS anyone can get started with Bootstrap. Also the Bootstrap official site has a good documentation. ·     ...