SPONSORS

Faster PHP Cloud Hosting
3422 views · 146 days ago

![Create Simple RESTful APIs using PHP & MySQL](https://images.ctfassets.net/vzl5fkwyme3u/5s6X92LpF8dGGVZEnXGRK0/387bfe60541987d308e8201ca5bb5d3f/api_blog_post.png?w=1000)

Hi Guys,

I am sharing you the way to create simple resful apis using php and mysql. We are creating 2 apis here

First is to Loggin a existing user and second is to get list of written blogs by logged in user.

#### Create any database, i am taking ```news``` as the database name here, After it create following 2 tables inside it.

```

CREATE TABLE `users` (

`id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

`name` varchar(100),

`email` varchar(100),

`password` varchar(100),

`createdAt` datetime NOT NULL,

`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP

);

CREATE TABLE `blogs` (

`id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

`user_id` int(11),

`title` varchar(255),

`summary` Tinytext,

`body` Text,

`createdAt` datetime NOT NULL,

`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP

);

```

#### Now putting some dummy data to read via the api

```

--create 2 entries in users table--

INSERT INTO `news`.`users` (`id`, `name`, `email`, `password`, `createdAt`, `updatedAt`) VALUES (1, 'jeetendra singh', '[email protected]', MD5('123456'), '2018-12-28 02:05:12', CURRENT_TIMESTAMP), (2, 'Manvik Singh chaudhary', '[email protected]', MD5('654321'), '2018-12-28 03:08:11', CURRENT_TIMESTAMP);

-- create 2 blogs by userid 1--

INSERT INTO `news`.`blogs` (`id`, `user_id`, `title`, `summary`, `body`, `createdAt`, `updatedAt`) VALUES (1, '1', 'Blog title 1 by jeetendra', 'Blog summary 1 by jeetendra', 'Blog body 1 by jeetendra', '2018-12-28 02:00:00', CURRENT_TIMESTAMP), (2, '1', 'Blog Title 2 by jeetendra ', 'Blog summary 2 by jeetendra ', 'Blog body 2 by jeetendra ', '2018-12-28 05:10:21', CURRENT_TIMESTAMP);

-- create 2 blogs by userid 2

INSERT INTO `news`.`blogs` (`id`, `user_id`, `title`, `summary`, `body`, `createdAt`, `updatedAt`) VALUES (3, '2', 'Blog title 1 by manvik', 'Blog summary 1 by manvik', 'Blog body 1 by manvik', '2018-12-28 02:00:00', CURRENT_TIMESTAMP), (4, '2', 'Blog Title 2 by manvik ', 'Blog summary 2 by manvik ', 'Blog body 2 by manvik ', '2018-12-28 05:10:21', CURRENT_TIMESTAMP);

```

#### After creating this create a index.php and put this code for Db connection, login and get all blog method

```

<?php

header("Content-Type: application/json; charset=UTF-8");

class DBClass {

private $host = "localhost";

private $username = "root";

private $password = ""; / /set your passwrd here

private $database = "news";

public $connection;

/ / get the database connection

public function connect(){

$this->connection = null;

try{

$this->connection = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->database, $this->username, $this->password);

$this->connection->exec("set names utf8");

}catch(PDOException $exception){

echo "Error: " . $exception->getMessage();

}

return $this->connection;

}

public function login($email,$password){

if($this->connection==null)

{

$this->connect();

}

$query = "SELECT id,name,email,createdAt,updatedAt from users where email= ? and password= ?";

$stmt = $this->connection->prepare($query);

$stmt->execute(array($email,md5($password)));

$ret= $stmt->fetchAll(PDO::FETCH_ASSOC);

return $ret;

}

public function get_all_blogs($Uid){

if($this->connection==null)

{

$this->connect();

}

$query = "SELECT b.*,u.id as Uid,u.email as Uemail,u.name as Uname from blogs b join users u on u.id=b.user_id where b.user_id= ?";

$stmt = $this->connection->prepare($query);

$stmt->execute(array($Uid));

$ret= $stmt->fetchAll(PDO::FETCH_ASSOC);

return $ret;

}

public function response($array)

{

echo json_encode($array);

exit;

}

}

/ /recieve the requests here / /

$return=array();

$obj = new DBClass();

if(isset($_GET['action']) && $_GET['action']!='')

{

if($_GET['action']=="login")

{

if(isset($_POST['email']) && isset($_POST['password']))

{

$UserData=$obj->login($_POST['email'],$_POST['password']);

if(count($UserData)>0)

{

$return['status']=1;

$return['_data_']=$UserData[0];

$return['message']='User Logged in Successfully.';

}

else

{

$return['status']=0;

$return['message']='Error:Invalid Email or Password!';

}

}

else

{

$return['status']=0;

$return['message']='Error:Email or Password not provided!';

}

}

elseif($_GET['action']=="UserBlogs")

{

if(isset($_POST['Uid']))

{

$blogs=$obj->get_all_blogs($_POST['Uid']);

if(count($blogs)>0)

{

$return['status']=1;

$return['_data_']=$blogs;

$return['message']='Success.';

}

else

{

$return['status']=0;

$return['message']='Error:Invalid UserId!';

}

}

else

{

$return['status']=0;

$return['message']='Error:User Id not provided!';

}

}

}

else

{

$return['status']=0;

$return['message']='Error:Action not provided!';

}

$obj->response($return);

$obj->connection=null;

?>

```

#### Now api file is set, just make the urls pretty(readable form) using .htaccess file, put following code in it

```

RewriteEngine On

RewriteRule ^api/(.*) index.php?action=$1

```

#### Now your Simple Restful Apis are ready to use, Now Let me show you the postman screenshot where i have used these apis.

**Login Api Call:**

![LOGIN API CALL](https://www.w3school.info/blogimages/login_api.png)

**User Post/Blog Api Call**

![USER BLOGS](https://www.w3school.info/blogimages/UserBlogs_api.png)

SPONSORS

Faster PHP Cloud Hosting