Home » Create RESTful API using PHP

Create RESTful API using PHP

Create RESTful API using PHP

In this Post We Will Explain About is Create RESTful API using PHP With Example and Demo.Welcome on Pakainfo.com – Examples, The best For Learn web development Tutorials,Demo with Example! Hi Dear Friends here u can know to How to create REST API for Android app using PHP, Slim and MySQL Example

In this post we will show you Best way to implement PHP Restful API Framework SLIM to Create REST API, hear for How to Create a REST API Using Slim Framework with Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.

Create RESTful API using Slim Framework

api
-- Slim //Pakainfo.com Slim Framework
---- db.php 
---- index.php //Pakainfo.com api index file
---- .htaccess //Pakainfo.com url redirection file. 
js
-- jquery.min.js
-- liveGetPost.js
css
-- style.css
index.html

Users Table

CREATE TABLE `students` (
`stud_id` int(11) AUTO_INCREMENT,
`studname` varchar(50),
`password` varchar(100),
`name` varchar(100),
`stud_img` varchar(200),
PRIMARY KEY (`stud_id`)
);

Updates Table

CREATE TABLE `stud_updates` (
`stud_update_id` int(11) AUTO_INCREMENT,
`stud_uptodate` text,
`user_id_fk` int(11), 
`created` int(11),
`ip` varchar(50),
PRIMARY KEY (`stud_update_id`)
);

Slim Framework

api/index.php

<?php
require 'db.php';
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim();

$app->get('/students','getStud');
$app->get('/stud_updates','getStudUpdates');
$app->post('/stud_updates', 'insertUpdate');
$app->delete('/stud_updates/delete/:stud_update_id','deleteUpdate');
$app->get('/students/search/:query','getUserSearch');

$app->run();

//Pakainfo.com GET http://www.Pakainfo.com/api/students
function getStud() {
$sql = "SELECT stud_id,studname,name,stud_img FROM students ORDER BY stud_id DESC";
try {
$db = getDB();
$stmt = $db->query($sql); 
$students = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo '{"students": ' . json_encode($students) . '}';
} catch(PDOException $e) {
//error_log($e->getMessage(), 3, '/var/tmp/phperror.log'); //Write error log
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}

//Pakainfo.com GET http://www.Pakainfo.com/api/stud_updates
function getStudUpdates() {
$sql = "SELECT A.stud_id, A.studname, A.name, A.stud_img, B.stud_update_id, B.stud_uptodate, B.created FROM students A, stud_updates B WHERE A.stud_id=B.user_id_fk  ORDER BY B.stud_update_id DESC";
try {
$db = getDB();
$stmt = $db->prepare($sql);
$stmt->execute(); 
$stud_updates = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo '{"stud_updates": ' . json_encode($stud_updates) . '}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}

//Pakainfo.com DELETE http://www.Pakainfo.com/api/stud_updates/delete/10
function deleteUpdate($stud_update_id)
{
$sql = "DELETE FROM stud_updates WHERE stud_update_id=:stud_update_id";
try {
$db = getDB();
$stmt = $db->prepare($sql); 
$stmt->bindParam("stud_update_id", $stud_update_id);
$stmt->execute();
$db = null;
echo true;
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}

// POST http://www.Pakainfo.com/api/stud_updates
function insertUpdate() {
//Pakainfo.com some code....
//Pakainfo.com some code....
}

function getUserUpdate($stud_update_id) {
//Pakainfo.com some code.....
//Pakainfo.com some code.....
}

// GET http://www.Pakainfo.com/api/students/search/sri
function getUserSearch($query) {
//Pakainfo.com some code.....
//Pakainfo.com some code....
}
?>

db.php

Read Also:  Convert JSON to CSV using PHP Example

We have to modify some fields database configuration(config.php) details, before simple trying this enable to settings php_pdo extension in step by step php.ini file.

<?php
function getDB() {
$dbhost="localhost";
$dbuser="studname";
$dbpass="[email protected]#$$$$";
$dbname="live24u";
$dbConnection = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass); 
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbConnection;
}
?>

Jquery

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="js/liveGetPost.js"></script>
<script>
$(document).ready(function()
{

var default_url="http://www.Pakainfo.com/project_name/";
var url,encodedata;
$("#update").focus();

/* Pakainfo.com Load Updates */
url=default_url+'api/stud_updates';
live_ajax_data('GET',url, function(data)
{
$.each(data.stud_updates, function(i,data)
{
var html="<div class='stbody' id='stbody"+data.stud_update_id+"'><div class='stimg'><img src='"+data.stud_img+"' class='stprofileimg'/></div><div class='sttext'><strong>"+data.name+"</strong>"+data.stud_uptodate+"<span id='"+data.stud_update_id+"' class='stdelete'>Delete</span></div></div>";
$(html).appendTo("#wrapperContent");
});
});

/*Pakainfo.com Insert Update */
$('body').on("click",'.stpostbutton',function()
{
var update=$('#update').val();
encode=JSON.stringify({
        "stud_uptodate": update,
        "stud_id": $('#stud_id').val()
        });
url=default_url+'api/stud_updates';
if(update.length>0)
{
	data_post_ajax_data(url,encode, function(data)
{
$.each(data.stud_updates, function(i,data)
{
	var html="<div class='stbody' id='stbody"+data.stud_update_id+"'><div class='stimg'><img src='"+data.stud_img+"' class='stprofileimg'/></div><div class='sttext'><strong>"+data.name+"</strong>"+data.stud_uptodate+"<span id='"+data.stud_update_id+"' class='stdelete'>Delete</span></div></div>";
	$("#wrapperContent").prepend(html);
	$('#update').val('').focus();
});
});
}

});

/*Pakainfo.com Delete Updates */
$('body').on("click",'.stdelete',function()
{
var ID=$(this).attr("id");
url=default_url+'api/stud_updates/delete/'+ID;
live_ajax_data('DELETE',url, function(data)
{
$("#stbody"+ID).fadeOut("slow");
});
});

});
</script>

HTML Code

<div>
<textarea id="update" class="stupdatebox"></textarea>
<input type="hidden" id="stud_id" value="Student Session Value">
<input type="submit" value="POST" class="stpostbutton">
</div>

<div id="wrapperContent"></div>

liveGetPost.js

//Pakainfo.com POST Ajax
function data_post_ajax_data(url, encodedata, success)
{
	$.ajax({
		type:"POST",
		url:url,
		data :encodedata,
		dataType:"json",
		restful:true,
		contentType: 'application/json',
		cache:false,
		timeout:20000,
		async:true,
		beforeSend :function(data) { },
		success:function(data){
		success.call(this, data);
		},
		error:function(data){
		alert("Error In Connecting");
		}
	});
}

//Pakainfo.com some GET and DELETE Ajax
function live_ajax_data(type, url, success)
{
	$.ajax({
	type:type,
	url:url,
	dataType:"json",
	restful:true,
	cache:false,
	timeout:20000,
	async:true,
	beforeSend :function(data) { },
	success:function(data){
		success.call(this, data);
	},
	error:function(data){
		alert("sorry Error In Connecting");
	}
});
}

You are Most welcome in my youtube Channel Please shubscibe my channel. and give me feedBackMore Details……
Angularjs Example

Read Also:  PHP RESTful Web Services Tutorial for beginners

Example

I hope you have Got What is How to create REST API for Android app using PHP, Slim and MySQL And how it works.I would Like to have FeaeBack From My Blog(Pakainfo.com) readers.Your Valuable FeedBack,Any Question,or any Comments abaout This Article(Pakainfo.com) Are Most Always Welcome.


Related FAQ

Here are some more FAQ related to this Article:

  1. Read Also:  REST API Insert Update Delete using PHP
  2. Read Also:  REST API CRUD Example in PHP with MySQLi
  3. Read Also:  Remove specific value from php array
  4. Read Also:  How to Create Flexify Image using PHP
  5. Read Also:  laravel 6 Retrieve data using jQuery Ajax
  6. Read Also:  PHP 30 days Trial Period Date checking using MYSQL
  7. Read Also:  Laravel 7/6 disable registration example
  8. Read Also:  VueJS Getters and Setters computed property
  9. Read Also:  wordpress Get Subcategories List custom PHP pages
  10. Read Also:  PHP Object Oriented Programming Tutorial Example

Leave a Comment

Your email address will not be published. Required fields are marked *