In this tutorial learn how to create an REST API for android or IOS/iphone application in php let's go with step by step.
API Tutorial
STEP 1 : create table in database, if you don't have database please create it.
STEP 2 : Create dbhelper.php file in folder of api and setup your mysql username and password with database
STEP 4 : call url in localhost
API Tutorial
STEP 1 : create table in database, if you don't have database please create it.
CREATE TABLE IF NOT EXISTS `categories` (`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,`name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,`details` text COLLATE utf8mb4_unicode_ci NOT NULL,`created_at` timestamp NULL DEFAULT NULL,`updated_at` timestamp NULL DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci AUTO_INCREMENT=2 ;
STEP 2 : Create dbhelper.php file in folder of api and setup your mysql username and password with database
<?php
class Dbhelper
{
public function dbconnect()
{
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "lsapi";
$conn = new mysqli($servername, $username, $password, $dbname);
return $conn;
}
public function SelQuery($sql){
$conn = $this->dbconnect();
$result = mysqli_query($conn, $sql);
return $result;
}
}
?>
STEP 3 : create category.php in api folder
<?php
/*
*
*/
// Create a new object
require_once('dbhelper.php');
$obj = new Category;
$token = $_GET['token']; //here you can post method for security
if($token=="12345"){
echo $obj->index();
}
class Category
{
public function index()
{
$dbhelper = new Dbhelper();
$sql = "SELECT * FROM categories";
$res = $dbhelper->SelQuery($sql);
$result = array();
if (mysqli_num_rows($res) > 0) {
$data = array();
while ($row = $res->fetch_assoc()) {
$det=array();
$det ['name'] = $row['name'];
$det['details'] = $row['details'];
$data[]=$det;
}
$result ['category']=$data;
$result ['status']=1;
}else{
$result ['error']="Categories are not available";
$result ['status']=0;
}
echo json_encode($result);
}
}
?>
http://localhost/api/category.php?token=12345
STEP 4: RESULT of category APIThis api now you can use in android or iphone application for developing new application.{"category":{"name":"Fruit","details":"This fruit category api testing"},"status":1}
No comments:
Post a Comment