আজকের পর্বে আমরা সার্ভার সাইডের কাজ করবো, অর্থাৎ RESTful API তৈরি করবো।  যদিও RESTful API  তে GET, POST, PUT, DELETE রিকোয়েস্ট সেন্ড করা হয় কিন্তু আমরা শুধু GET এবং POST এর মাধ্যমেই API টি তৈরি করবো। 

 

আজকে শুধু একটি php ফাইলেই  সব কোড লিখা হয়েছে, নিচে ফাইলটির কোড দেওয়া হলো, এবং সব শেষে ইউটিউবের লিঙ্ক দেওয়া হলো 

 

api.php: 

<?php

$conn = new mysqli("localhost", "root", "123", "vuephpcrud");
if($conn->connect_error){
	die("Could not connect to database!");
}

$res = array('error' => false);

$action = 'read';

if(isset($_GET['action'])){
	$action = $_GET['action'];
}


if($action == 'read'){
	$result = $conn->query("SELECT * FROM `users`");
	$users = array();

	while($row = $result->fetch_assoc()){
		array_push($users, $row);
	}

	$res['users'] = $users;
}

if($action == 'create'){

	$username = $_POST['username'];
	$email = $_POST['email'];
	$mobile = $_POST['mobile'];

	$result = $conn->query("INSERT INTO `users` (`username`, `email`, `mobile`) VALUES ('$username', '$email', '$mobile') ");
	
	if($result){
		$res['message'] = "User added successfully";
	} else{
		$res['error'] = true;
		$res['message'] = "Could not insert user";
	}
}

if($action == 'update'){
	$id = $_POST['id'];
	$username = $_POST['username'];
	$email = $_POST['email'];
	$mobile = $_POST['mobile'];

	$result = $conn->query("UPDATE `users` SET `username` = '$username', `email` = '$email', `mobile` = '$mobile' WHERE `id` = '$id'");
	
	if($result){
		$res['message'] = "User updated successfully";
	} else{
		$res['error'] = true;
		$res['message'] = "Could not update user";
	}

}

if($action == 'delete'){
	$id = $_POST['id'];
	

	$result = $conn->query("DELETE FROM `users` WHERE `id` = '$id'");
	
	if($result){
		$res['message'] = "User deleted successfully";
	} else{
		$res['error'] = true;
		$res['message'] = "Could not delete user";
	}

}


$conn->close();

header("Content-type: application/json");
echo json_encode($res);
die();

ইউটিউব লিঙ্ক :   Vue php CRUD Part-2