Rest api Using CURD

Two folder:-

action.php

<?php

//action.php

if(isset($_POST["action"]))
{
if($_POST["action"] == 'insert')
{
$form_data = array(
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name']
);
$api_url = "http://localhost/rest-api-crud-using-php/api/test_api.php?action=insert";  //change this url as per your folder path for api folder
$client = curl_init($api_url);
curl_setopt($client, CURLOPT_POST, true);
curl_setopt($client, CURLOPT_POSTFIELDS, $form_data);
curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($client);
curl_close($client);
$result = json_encode($response, true);
foreach($result as $keys => $values)
{
if($result[$keys]['success'] == '1')
{
echo 'insert';
}
else
{
echo 'error';
}
}
}

if($_POST["action"] == 'fetch_single')
{
$id = $_POST["id"];
$api_url = "http://localhost/rest-api-crud-using-php/api/test_api.php?action=fetch_single&id=".$id."";  //change this url as per your folder path for api folder
$client = curl_init($api_url);
curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($client);
echo $response;
}
if($_POST["action"] == 'update')
{
$form_data = array(
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'id' => $_POST['hidden_id']
);
$api_url = "http://localhost/rest-api-crud-using-php/api/test_api.php?action=update";  //change this url as per your folder path for api folder
$client = curl_init($api_url);
curl_setopt($client, CURLOPT_POST, true);
curl_setopt($client, CURLOPT_POSTFIELDS, $form_data);
curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($client);
curl_close($client);
$result = json_decode($response, true);
foreach($result as $keys => $values)
{
if($result[$keys]['success'] == '1')
{
echo 'update';
}
else
{
echo 'error';
}
}
}
if($_POST["action"] == 'delete')
{
$id = $_POST['id'];
$api_url = "http://localhost/rest-api-crud-using-php/api/test_api.php?action=delete&id=".$id.""; //change this url as per your folder path for api folder
$client = curl_init($api_url);
curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($client);
echo $response;
}
}


?>


fetch.php


<?php

//fetch.php

$api_url = "http://localhost/rest-api-crud-using-php/api/test_api.php?action=fetch_all";

$client = curl_init($api_url);

curl_setopt($client, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($client);

$result = json_decode($response);

$output = '';

if(count($result) > 0)
{
foreach($result as $row)
{
$output .= '
<tr>
<td>'.$row->first_name.'</td>
<td>'.$row->last_name.'</td>
<td><button type="button" name="edit" class="btn btn-warning btn-xs edit" id="'.$row->id.'">Edit</button></td>
<td><button type="button" name="delete" class="btn btn-danger btn-xs delete" id="'.$row->id.'">Delete</button></td>
</tr>
';
}
}
else
{
$output .= '
<tr>
<td colspan="4" align="center">No Data Found</td>
</tr>
';
}

echo $output;

?>


index.php


<!DOCTYPE html>
<html>
<head>
<title>PHP Mysql REST API CRUD</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<br />

<h3 align="center">PHP Mysql REST API CRUD</h3>
<br />
<div align="right" style="margin-bottom:5px;">
<button type="button" name="add_button" id="add_button" class="btn btn-success btn-xs">Add</button>
</div>

<div class="table-responsive">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</body>
</html>

<div id="apicrudModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form method="post" id="api_crud_form">
<div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Add Data</h4>
      </div>
      <div class="modal-body">
      <div class="form-group">
        <label>Enter First Name</label>
        <input type="text" name="first_name" id="first_name" class="form-control" />
        </div>
        <div class="form-group">
        <label>Enter Last Name</label>
        <input type="text" name="last_name" id="last_name" class="form-control" />
        </div>
    </div>
    <div class="modal-footer">
    <input type="hidden" name="hidden_id" id="hidden_id" />
    <input type="hidden" name="action" id="action" value="insert" />
    <input type="submit" name="button_action" id="button_action" class="btn btn-info" value="Insert" />
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
</form>
</div>
  </div>
</div>


<script type="text/javascript">
$(document).ready(function(){

fetch_data();

function fetch_data()
{
$.ajax({
url:"fetch.php",
success:function(data)
{
$('tbody').html(data);
}
})
}

$('#add_button').click(function(){
$('#action').val('insert');
$('#button_action').val('Insert');
$('.modal-title').text('Add Data');
$('#apicrudModal').modal('show');
});

$('#api_crud_form').on('submit', function(event){
event.preventDefault();
if($('#first_name').val() == '')
{
alert("Enter First Name");
}
else if($('#last_name').val() == '')
{
alert("Enter Last Name");
}
else
{
var form_data = $(this).serialize();
$.ajax({
url:"action.php",
method:"POST",
data:form_data,
success:function(data)
{
fetch_data();
$('#api_crud_form')[0].reset();
$('#apicrudModal').modal('hide');
if(data == 'insert')
{
alert("Data Inserted using PHP API");
}
if(data == 'update')
{
alert("Data Updated using PHP API");
}
}
});
}
});

$(document).on('click', '.edit', function(){
var id = $(this).attr('id');
var action = 'fetch_single';
$.ajax({
url:"action.php",
method:"POST",
data:{id:id, action:action},
dataType:"json",
success:function(data)
{
$('#hidden_id').val(id);
$('#first_name').val(data.first_name);
$('#last_name').val(data.last_name);
$('#action').val('update');
$('#button_action').val('Update');
$('.modal-title').text('Edit Data');
$('#apicrudModal').modal('show');
}
})
});

$(document).on('click', '.delete', function(){
var id = $(this).attr("id");
var action = 'delete';
if(confirm("Are you sure you want to remove this data using PHP API?"))
{
$.ajax({
url:"action.php",
method:"POST",
data:{id:id, action:action},
success:function(data)
{
fetch_data();
alert("Data Deleted using PHP API");
}
});
}
});

});
</script>

Folder Name api

api.php

<?php

//Api.php

class API
{
private $connect = '';

function __construct()
{
$this->database_connection();
}

function database_connection()
{
$this->connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
}

function fetch_all()
{
$query = "SELECT * FROM tbl_sample ORDER BY id";
$statement = $this->connect->prepare($query);
if($statement->execute())
{
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$data[] = $row;
}
return $data;
}

}

function insert()
{
if(isset($_POST["first_name"]))
{
$form_data = array(
':first_name' => $_POST["first_name"],
':last_name' => $_POST["last_name"]
);
$query = "
INSERT INTO tbl_sample
(first_name, last_name) VALUES
(:first_name, :last_name)
";
$statement = $this->connect->prepare($query);
if($statement->execute($form_data))
{
$data[] = array(
'success' => '1'
);
}
else
{
$data[] = array(
'success' => '0'
);
}
}
else
{
$data[] = array(
'success' => '0'
);
}
return $data;
}

function fetch_single($id)
{
$query = "SELECT * FROM tbl_sample WHERE id='".$id."'";
$statement = $this->connect->prepare($query);
if($statement->execute())
{
foreach($statement->fetchAll() as $row)
{
$data['first_name'] = $row['first_name'];
$data['last_name'] = $row['last_name'];
}
return $data;
}
}

function update()
{
if(isset($_POST["first_name"]))
{
$form_data = array(
':first_name' => $_POST['first_name'],
':last_name' => $_POST['last_name'],
':id' => $_POST['id']
);
$query = "
UPDATE tbl_sample
SET first_name = :first_name, last_name = :last_name
WHERE id = :id
";
$statement = $this->connect->prepare($query);
if($statement->execute($form_data))
{
$data[] = array(
'success' => '1'
);
}
else
{
$data[] = array(
'success' => '0'
);
}
}
else
{
$data[] = array(
'success' => '0'
);
}
return $data;
}
function delete($id)
{
$query = "DELETE FROM tbl_sample WHERE id = '".$id."'";
$statement = $this->connect->prepare($query);
if($statement->execute())
{
$data[] = array(
'success' => '1'
);
}
else
{
$data[] = array(
'success' => '0'
);
}
return $data;
}
}

?>

test.php

<?php

//test_api.php

include('Api.php');

$api_object = new API();

if($_GET["action"] == 'fetch_all')
{
$data = $api_object->fetch_all();
}

if($_GET["action"] == 'insert')
{
$data = $api_object->insert();
}

if($_GET["action"] == 'fetch_single')
{
$data = $api_object->fetch_single($_GET["id"]);
}

if($_GET["action"] == 'update')
{
$data = $api_object->update();
}

if($_GET["action"] == 'delete')
{
$data = $api_object->delete($_GET["id"]);
}

echo json_encode($data);

?>


Database:-

  CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,

 `first_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `last_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Comments

Popular posts from this blog

Forgot password using codeigniter

Insert and Update or Edit Data using jQuery Dialogify with PHP Ajax

Facebook Login With Codeigniter