Build REST CRUD APIs with PHP and MySQL

Hello everyone. today we will learn how to develop REST-style CRUD APIs with PHP and MySQL.

After completing this tutorial what we will build? 

We will build REST API  CRUD features: 
  1. GET - Fetch all User       : /php-mysql-crud-api/read.php
  2. GET - Get User by ID     : /php-mysql-crud-api/single_user.php/?id=172
  3. POST - Create User         : /php-mysql-crud-api/create.php
  4. PUT - Edit User Details   : /php-mysql-crud-api/update.php
  5. DELETE - Delete User    : /php-mysql-crud-api/delete.php/?id=172

Project Directory:


Setting Up Database:

Create Database "user_db" and create table "user"

--
-- Database: `user_db`
--
-- --------------------------------------------------------
--
-- Table structure for table `user`
--

CREATE TABLE `user` (
`id` bigint(20) UNSIGNED NOT NULL,
`first_name` varchar(50) NOT NULL,
`last_name` varchar(50) NOT NULL,
`email_id` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

ALTER TABLE `user`
ADD UNIQUE KEY `id` (`id`);

ALTER TABLE `user`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=70;
COMMIT;

Database Connection [database.php]:

<?php
class DB {
private $host = "localhost";
private $db = "user_db";
private $username = "root";
private $password = "";

public $conn;

public function getConnection(){
$this->conn = null;
try{
$this->conn = new PDO("mysql:host=" . $this->host .
";dbname=" . $this->db, $this->username, $this->password);
$this->conn->exec("set names utf8");
}catch(PDOException $exception){
echo "Database not connected: " . $exception->getMessage();
}
return $this->conn;
}
}
?>

Create User Class[user.php]:

<?php
class User{

// conn
private $conn;

// table
private $dbTable = "user";

// col
public $id;
public $first_name;
public $last_name;
public $email_id;
// db conn
public function __construct($db){
$this->conn = $db;
}

// GET Users
public function getUsers(){
$sqlQuery = "SELECT id, first_name, last_name, email_id
FROM " . $this->dbTable . "";
$stmt = $this->conn->prepare($sqlQuery);
$stmt->execute();
return $stmt;
}

// CREATE User
public function createUser(){
$sqlQuery = "INSERT INTO
". $this->dbTable ."
SET
first_name = :first_name,
last_name = :last_name,
email_id = :email_id";
$stmt = $this->conn->prepare($sqlQuery);
// sanitize
$this->first_name=htmlspecialchars(strip_tags($this->first_name));
$this->last_name=htmlspecialchars(strip_tags($this->last_name));
$this->email_id=htmlspecialchars(strip_tags($this->email_id));
// bind data
$stmt->bindParam(":first_name", $this->first_name);
$stmt->bindParam(":last_name", $this->last_name);
$stmt->bindParam(":email_id", $this->email_id);
if($stmt->execute()){
return true;
}
return false;
}

// GET User
public function getSingleUser(){
$sqlQuery = "SELECT
id,
first_name,
last_name,
email_id
FROM
". $this->dbTable ."
WHERE
id = ?
LIMIT 0,1";

$stmt = $this->conn->prepare($sqlQuery);

$stmt->bindParam(1, $this->id);

$stmt->execute();

$dataRow = $stmt->fetch(PDO::FETCH_ASSOC);
$this->first_name = $dataRow['first_name'];
$this->last_name = $dataRow['last_name'];
$this->email_id = $dataRow['email_id'];
}

// UPDATE User
public function updateUser(){
$sqlQuery = "UPDATE
". $this->dbTable ."
SET
first_name = :first_name,
last_name = :last_name,
email_id = :email_id
WHERE
id = :id";
$stmt = $this->conn->prepare($sqlQuery);
$this->first_name=htmlspecialchars(strip_tags($this->first_name));
$this->last_name=htmlspecialchars(strip_tags($this->last_name));
$this->email_id=htmlspecialchars(strip_tags($this->email_id));
$this->id=htmlspecialchars(strip_tags($this->id));
// bind data
$stmt->bindParam(":first_name", $this->first_name);
$stmt->bindParam(":last_name", $this->last_name);
$stmt->bindParam(":email_id", $this->email_id);
$stmt->bindParam(":id", $this->id);
if($stmt->execute()){
return true;
}
return false;
}

// DELETE User
function deleteUser(){
$sqlQuery = "DELETE FROM " . $this->dbTable . " WHERE id = ?";
$stmt = $this->conn->prepare($sqlQuery);
$this->id=htmlspecialchars(strip_tags($this->id));
$stmt->bindParam(1, $this->id);
if($stmt->execute()){
return true;
}
return false;
}

}
?>

Create User [create.php]:

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET,POST,PUT,DELETE");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type,
Access-Control-Allow-Headers, Authorization, X-Requested-With");

include_once 'config/database.php';
include_once 'class/user.php';

$database = new DB();
$db = $database->getConnection();

$item = new User($db);

$data = json_decode(file_get_contents("php://input"));

$item->first_name = $data->first_name;
$item->last_name = $data->last_name;
$item->email_id = $data->email_id;
if($item->createUser()){
echo json_encode("User created.");
} else{
echo json_encode("Failed to create user.");
}
?>

Get User Records [read.php]:

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
include_once 'config/database.php';
include_once 'class/user.php';

$database = new DB();
$db = $database->getConnection();

$items = new User($db);

$stmt = $items->getUsers();
$itemCount = $stmt->rowCount();

if($itemCount > 0){
$userArr = array();

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$e = array(
"id" => $id,
"first_name" => $first_name,
"last_name" => $last_name,
"email_id" => $email_id
);

array_push($userArr, $e);
}
echo json_encode($userArr);
}
?>

Get User By Id [single_user.php]:

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json;");
include_once 'config/database.php';
include_once 'class/user.php';

$database = new DB();
$db = $database->getConnection();

$item = new User($db);

$item->id = isset($_GET['id']) ? $_GET['id'] : die();
$item->getSingleUser();

if($item->first_name!= null){
$user_Arr = array(
"id" => $item->id,
"first_name" => $item->first_name,
"last_name" => $item->last_name,
"email_id" => $item->email_id
);
http_response_code(200);
echo json_encode($user_Arr);
}
else{
http_response_code(404);
echo json_encode("User not found");
}
?>

Update User [update.php]:

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET,POST,PUT,DELETE");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type,
Access-Control-Allow-Headers, Authorization, X-Requested-With");

include_once 'config/database.php';
include_once 'class/user.php';
$database = new DB();
$db = $database->getConnection();
$item = new User($db);
$data = json_decode(file_get_contents("php://input"));
$item->id = $data->id;
$item->first_name = $data->first_name;
$item->last_name = $data->last_name;
$item->email_id = $data->email_id;
if($item->updateUser()){
echo json_encode("User record updated.");
} else{
echo json_encode("User record could not be updated.");
}
?>

Delete User [delete.php]:

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: DELETE");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type,
Access-Control-Allow-Headers, Authorization, X-Requested-With");


include_once 'config/database.php';
include_once 'class/user.php';

$database = new DB();
$db = $database->getConnection();

$item = new User($db);

$item->id = isset($_GET['id']) ? $_GET['id'] : die();

if($item->deleteUser()){
echo json_encode("User deleted.");
} else{
echo json_encode("Data could not be deleted");
}
?>

Verify REST APIs

1. Add User


2. Get Single User


3. Fetch All Users


4. Update User


5. Delete User

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete