I’m the author of InderCodes and I want to share the core of the application with you.
I’ll explain you the CURD operation via API for one complete module.
PROJECT CODE AVAILABLE ON GITHUB:
You need to create two files to test the project:
- database.php
- user.php
database.php contains below code:
<?php
//********** Database Connections **************//
//MySqli Driver used$mysql_host = “localhost”;
$username = “root”;
$password = “”;
$mysql_database = “php_api”;$con = mysqli_connect($mysql_host, $username, $password, $mysql_database);
// Check connection
if (mysqli_connect_errno()) {
echo “Failed to connect to MySQL: ” . mysqli_connect_error();
}
This file we’ve used to connect with our MySQL database. In the demo project I’ve created php_api database.
php_api databse contain one table users. You can use the below SQL Script to create the same.
— Table structure for table `users`
—CREATE TABLE `users` (
`id` int(11) NOT NULL,
`first_name` varchar(50) NOT NULL,
`last_name` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;INSERT INTO `users` (`id`, `first_name`, `last_name`, `email`) VALUES
(1, ‘Steve’, ‘Jobs’, ‘steve@apple.com’);ALTER TABLE `users`
ADD PRIMARY KEY (`id`);—
— AUTO_INCREMENT for dumped tables
——
— AUTO_INCREMENT for table `users`
—
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
To test the API i recommend to use Postman.
After creating database we have new users.php file
users.php
<?php
include(“Database.php”);
switch ($_GET[‘function’]) {
case ‘users_list’: users_list();
break;
case ‘add_user’: add_user();
break;
case ‘edit_user’: edit_user();
break;
case ‘delete_user’: delete_user();
break;
}
//http://localhost/php_api/users.php?function=users_list
function users_list() {//Accessing Connection details by using Global variable
$db = $GLOBALS[‘con’];$sql = “SELECT id, first_name, last_name FROM users;”;
if ($result = mysqli_query($db, $sql)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {$rows[] = array(‘data’ => $row);
}
mysqli_free_result($result);$json_op = array(
“status_code” => 101,
“msg” => “Users List successfully displayed.”,
“users_list” => $rows
);
} else {$json_op = array(
“status_code” => 102,
“msg” => “No User available.”,
“event_list” => []
);
}@mysqli_close($db);
/* Output header */
header(‘Content-type: application/json’);
echo json_encode($json_op);
}
}//http://localhost/php_api/users.php?function=add_user
/*
Need to pass three parameter via POST
1. first_name
2. last_name
3. email
*/
function add_user() {$first_name = $_POST[‘first_name’];
$last_name = $_POST[‘last_name’];
$email = $_POST[’email’];//Validating required fields
if (!empty($first_name) || !empty($email)) {
$db = $GLOBALS[‘con’];$sql = “INSERT INTO users (first_name, last_name, email)
VALUES (‘$first_name’,’$last_name’, ‘$email’);”;if (mysqli_query($db, $sql)) {
$json_op = array(
“status_code” => 103,
“msg” => “User added successfully.”
);
} else {
$json_op = array(
“status_code” => 104,
“error” => $db->error,
“msg” => “Event failed to add.”
);
}@mysqli_close($db);
/* Output header */
header(‘Content-type: application/json’);
echo json_encode($json_op);
}
}//http://localhost/php_api/users.php?function=edit_user
/*
Need to pass id parameter via POST with all other 3 parameters
id parameter will identify the row to update1. id
2. first_name
3. last_name
4. email*/
function edit_user() {$id = $_POST[‘id’];
$first_name = $_POST[‘first_name’];
$last_name = $_POST[‘last_name’];
$email = $_POST[’email’];if (!empty($id) || !empty($first_name) || !empty($email)) {
$db = $GLOBALS[‘con’];$sql = “UPDATE users SET first_name = ‘$first_name’,
last_name = ‘$last_name’, email = ‘$email’
WHERE id = ‘$id’;”;if (mysqli_query($db, $sql)) {
$json_op = array(
“status_code” => 105,
“msg” => “User updated successfully.”
);
} else {
$json_op = array(
“status_code” => 106,
“error” => $db->error,
“msg” => “User failed to update.”
);
}@mysqli_close($db);
/* Output header */
header(‘Content-type: application/json’);
echo json_encode($json_op);
}
}//http://localhost/php_api/users.php?function=delete_user
/*
Need to pass id parameter via POST
*/
function delete_user() {$id = $_POST[‘id’];
if (!empty($id)) {
$db = $GLOBALS[‘con’];$sql = “DELETE FROM users WHERE id = $id;”;
if (mysqli_query($db, $sql)) {
$json_op = array(
“status_code” => 107,
“msg” => “User deleted successfully.”
);
} else {
$json_op = array(
“status_code” => 108,
“error” => $db->error,
“msg” => “User failed to delete.”
);
}@mysqli_close($db);
/* Output header */
header(‘Content-type: application/json’);
echo json_encode($json_op);
}
}
In the above file we’ve four functions:
- users_list
- add_user
- edit_user
- delete_user
Use POST method to pass any parameter from API.
You can access the API by below URL’s:
- http://localhost/php_api/users.php?function=users_list
- http://localhost/php_api/users.php?function=add_user (need to pass 3 parameters: first_name, last_name, email)
- http://localhost/php_api/users.php?function=edit_user (need to pass 4 parameters: id, first_name, last_name, email)
- http://localhost/php_api/users.php?function=delete_user (need to pass 1 parameter: id)
OUTPUT : users_list
{
“status_code“: 101,
“msg“: “Users List successfully displayed.“,
“users_list“: [
{
“data”:{
“0”: “1”,
“1”: “Steve”,
“2”: “Jobs”,
“id”: “1”,
“first_name”: “Steve”,
“last_name”: “Jobs”
}
}
]
}
Status Code: It works as a error code which helps you to track the API failure status.
msg: It print the success/failure message
Remaining all are the data returned by API in JSON format.
Thanks & Regards,
Inderjeet Singh
Admin, what is the need of status code in above CURD example?
LikeLike
Status Code helps to track the API’s success or failure stage.
Its good practice to provide a status code for every output.
LikeLike