Beginner PHP Web API Tutorial

We will learn how to create a simple REST API in PHP. Enjoy our step-by-step tutorial below! But before we need to know about REST and API.

Beginner PHP Web API Tutorial

REST stands for “REpresentational State Transfer”. It is to manage the information over the internet. REST concepts are referred to as resources. A representation of a resource must be stateless.

API stands for “Application Programming Interface”. It is a set or rules that allows one piece of software application to talk to another. Those “rules” can include create, read, update and delete operations.

Manually create the database in phpMyAdmin

On the new page that opens you will see a list of all the current tables inside the database and a section named Create table. In that section, in the Name field you should input the desired new name of the table and then select the number of columns that the table should have via the Number of columns drop-down. When ready, click the Go button to create the table.

Beginner PHP Web API Tutorial

Beginner PHP Web API Tutorial

more details : Rest API

Create Database connection using ‘dbconfig.php’ file.

class Database{
 
    // specify your own database credentials
    private $host = "localhost";
    private $db_name = "database_name";
    private $username = "username_of_database";
    private $password = "password_of_database";
    public $conn;
 
    // get the database connection
    public function getConnection(){
 
        $this->conn = null;
 
        try{
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
            $this->conn->exec("set names utf8");
        }catch(PDOException $exception){
            echo "Connection error: " . $exception->getMessage();
        }
 
        return $this->conn;
    }
}

Making several GET, POST requests on server

// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
 
// include database and object files
include_once './config/dbconfig.php';
include_once './models/models.php';

// instantiate database and product object
$database = new Database();
$db = $database->getConnection();

if ($db->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
// echo json_encode("Connected successfully");

if( $_POST['action_name'] == 'products' || $_POST['action_code'] == '127') {

// initialize object
    $products = new Product($db);

    // query products
    $stmt = $products->read();
    $num = $stmt->rowCount();

     // check if more than 0 record found
    try {
        if($num>0){
            // product array
            $product_arr=array();
            $product_arr["data"]=array();
             // retrieve our table contents
            // fetch() is faster than fetchAll()
            // http://stackoverflow.com/questions/2770630/pdofetchall-vs-pdofetch-in-a-loop
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
                // extract row
                // this will make $row['name'] to
                // just $name only
                extract($row);
        
                $product_item=array(
                    "id" => $id,
                    "product" => $Title
                );
        
                array_push($product_arr["data"], $product_item);
            }
            $product_arr["code"]= 200;
            $product_arr["message"]= "success";
            echo json_encode($product_arr);
        }
    }
    catch(Exception $e) {
            echo json_encode(
        array("code" => 100,
                "message" => " No Data found")
    );
    }
}
else {
	echo json_encode(
    array("code" => 100,
            "message" => "Incorrect Action name or code")
);
}

Create Product class file to get the column from the table.

Here we will create, read, update and delete database records.

class Product{
 
    // database connection and table name
    private $conn;
    private $table_name = "products";
 
    // object properties
    public $id;
    public $name;
 
    // constructor with $db as database connection
    public function __construct($db){
        $this->conn = $db;
    }

    function read() {
 
        // select all query
        $query = "SELECT id , Title , calcprice FROM " . $this->table_name . "";
     
        // prepare query statement
        $stmt = $this->conn->prepare($query);
     
        // execute query
        $stmt->execute();
     
        return $stmt;
    }

}

Hey there, thanks for your time reading my article and for responding. I love developing and blogging, as you have in my article. I will try to go briefly through your points. If something is not clear, feel free to comment.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s