Giter Club home page Giter Club logo

php_rest_myblog's Introduction

PHP REST API

This is a simple PHP REST API from scratch with no framework.

Quick Start

Import the myblog.sql file, change the params in the config/Database.php file to your own

App Info

Author

Brad Traversy Traversy Media

Version

1.0.0

License

This project is licensed under the MIT License

php_rest_myblog's People

Contributors

bradtraversy avatar maxwellenemuo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php_rest_myblog's Issues

how to fetch multiple rows with same category id ?

i have a VIEW and it joined with two tables. i want to read rows that some subject id. how can i do this?
example :
[
{
"id" : 1.
"name" : "book",
"category_id": 2
}
{
"id" : 1.
"name" : "book",
"category_id": 2
}
{
"id" : 1.
"name" : "nootbook",
"category_id": 1
}

]

i want to fetch rows with category id = 2

Please help

I can still access create.php via GET method and it's adding a blank record to database


Notice: Trying to get property 'title' of non-object in D:\APP\xampp7\htdocs\2018\php_rest_myblog-master\api\post\create.php on line 21

Notice: Trying to get property 'body' of non-object in D:\APP\xampp7\htdocs\2018\php_rest_myblog-master\api\post\create.php on line 22

Notice: Trying to get property 'author' of non-object in D:\APP\xampp7\htdocs\2018\php_rest_myblog-master\api\post\create.php on line 23

Notice: Trying to get property 'category_id' of non-object in D:\APP\xampp7\htdocs\2018\php_rest_myblog-master\api\post\create.php on line 24

{"message":"Post Created"}

what is the function to check Access Method?

update does not actually update

I went thru the code and compared yours and mine and I can not get update to work.
There are 4 errors, Line 22, 23, 24, 25
PHP Notice: Trying to get property 'id' of non-object in...
This repeats for 'id', 'title','body',author'
But the code is the same when I compare the two files.

When I create the query for update, there is no error in POSTMAN. The error is in the bowels of server logs

JSON or URL Encoded

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

Hey. I'm playing with this code and for me on my local MAMP environment and using INSOMNIA REST client, I get the data as a query string instead of JSON. Insomnia is set to POST and send the data as Form URL Encoded.

I have no preference of one or the other, but do you know what's triggering the difference in output formats?

Error running api / post / read.php

I have adjusted to the name of the folder and file as you created, but I still have problems like below. I have analyzed it several times, but it still fails. Please help me.

PHP Warning:  include(../../config/Database.php): failed to open stream: No such file or directory in C:\xampp\htdocs\restfulphp1\api\post\read.php on line 5
PHP Stack trace:
PHP   1. {main}() C:\xampp\htdocs\restfulphp1\api\post\read.php:0

Warning: include(../../config/Database.php): failed to open stream: No such file or directory in C:\xampp\htdocs\restfulphp1\api\post\read.php on line 5

Call Stack:
    0.0003     406744   1. {main}() C:\xampp\htdocs\restfulphp1\api\post\read.php:0

PHP Warning:  include(): Failed opening '../../config/Database.php' for inclusion (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\restfulphp1\api\post\read.php on line 5
PHP Stack trace:
PHP   1. {main}() C:\xampp\htdocs\restfulphp1\api\post\read.php:0

Warning: include(): Failed opening '../../config/Database.php' for inclusion (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\restfulphp1\api\post\read.php on line 5

Call Stack:
    0.0003     406744   1. {main}() C:\xampp\htdocs\restfulphp1\api\post\read.php:0

PHP Warning:  include(../../models/Post.php): failed to open stream: No such file or directory in C:\xampp\htdocs\restfulphp1\api\post\read.php on line 6
PHP Stack trace:
PHP   1. {main}() C:\xampp\htdocs\restfulphp1\api\post\read.php:0

Warning: include(../../models/Post.php): failed to open stream: No such file or directory in C:\xampp\htdocs\restfulphp1\api\post\read.php on line 6

Call Stack:
    0.0003     406744   1. {main}() C:\xampp\htdocs\restfulphp1\api\post\read.php:0

PHP Warning:  include(): Failed opening '../../models/Post.php' for inclusion (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\restfulphp1\api\post\read.php on line 6
PHP Stack trace:
PHP   1. {main}() C:\xampp\htdocs\restfulphp1\api\post\read.php:0

Warning: include(): Failed opening '../../models/Post.php' for inclusion (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\restfulphp1\api\post\read.php on line 6

Call Stack:
    0.0003     406744   1. {main}() C:\xampp\htdocs\restfulphp1\api\post\read.php:0

PHP Fatal error:  Uncaught Error: Class 'Databa
Fatal error: Uncaught Error: Class 'Database' not found in C:\xampp\htdocs\restfulphp1\api\post\read.php on line 14

Error: Class 'Database' not found in C:\xampp\htdocs\restfulphp1\api\post\read.php on line 14

Call Stack:
    0.0003     406744   1. {main}() C:\xampp\htdocs\restfulphp1\api\post\read.php:0

se' not found in C:\xampp\htdocs\restfulphp1\api\post\read.php:14
Stack trace:
#0 {main}
  thrown in C:\xampp\htdocs\restfulphp1\api\post\read.php on line 14

I use version:
Apache/2.4.39 (Win64) OpenSSL/1.1.1b PHP/7.3.5
Database client version: libmysql - mysqlnd 5.0.12-dev - 20150407 - $Id: 7cc7cc96e675f6d72e5cf0f267f48e167c2abb23 $
PHP extension: mysqliDocumentation curlDocumentation mbstringDocumentation
PHP version: 7.3.5

Uncaught PDOException: SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected in E:\Work\Aptech\XAmpp\htdocs\myproject\rest\models\Post.php:45

I'm having this trouble, any suggests?
Thank you for the codes

Post.php
`<?php
class Post{
//DB
private $conn;
private $table = 'posts';

//post properties
public $id;
public $category_id;
public $category_name;
public $title;
public $body;
public $author;
public $created_at;

//constructor
public function __construct($db)
{
	$this->conn = $db;
}
//get posts

public function read(){
	//creat query
	$query = 'SELECT 
	C.name as category_name,
    p.id,
    p.category_id,
    p.title,
    p.body,
    p.author,
    p.created_at    
    FROM
    ' .$this->table. ' p
    LEFT JOIN 
     categories c ON p.category_id = c.id
     ORDER BY 
     p.created_at DESC';


     //prepare statement
     $stmt = $this->conn->prepare($query);

     //execute
     $stmt->execute();

     return $stmt;
}

}`

Database.php
`<?php
/**
*
*/
class Database
{
private $host = 'localhost';
private $db_name = 'testt';
private $username = 'root';
private $password = '';
private $conn;

//DB connect
public function connect()
{
	$this->conn = null;

	try{
		$this->conn = new PDO('mysql:host='.$this->host.';dbname ='.$this->db_name,$this->username, $this->password);
		$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

	}
	catch(PDOException $e){
		echo 'Connection Error: '.$e->getMessage();
	}
	return $this->conn;
}

}
?>`

read.php
`<?php
//Headers
header('Access-Control-Allow-Origin: *');
header('Content-Type:application/json');

include_once 'E:/Work/Aptech/XAmpp/htdocs/myproject/rest/Database.php';
include_once 'E:/Work/Aptech/XAmpp/htdocs/myproject/rest/models/Post.php';

//Install DB & connect
$database = new Database();
$db = $database->connect();

//Instantiate Post object
$post = new Post($db);

//Blog post query
$result = $post->read();
//Get row count
$num = $result->rowCount();

//check if any posts
if($num>0)
{
//post array
$posts_arr = array();
$posts_arr['data']=array();

while($row = $result->fetch(PDO::FETCH_ASSOC)){
	extract($row);

	$post_item = array(
    'id'=>$id,
    'title'=>$title,
    'body'=> html_entity_decode($body),
    'author'=>$author,
    'category_id'=>$category_id,
    'category_name'=> $category_name
	);

    //push to "data"
    array_push($posts_arr['data'], $post_item);
}

//turn to JSON &output
echo json_encode($posts_arr);

}else{
//no post
echo json_encode(
array('message'=>'No Posts Found')
);
}
`

Minor Bug in Update and Delete Api

Minor bug in Update and Delete API Created. The bug I faced is that when we execute the API's like update and delete in Postman Software for the query 'DELETE FROM ' . $this->table . ' WHERE id = :id' when the "id" is not in the Database still the Query executes and does not throw any error.
So, i wrote a Check() function in Post.php which will check if any entry with following "id" is present or not and will throw an error accordingly.

I will be contributing tomorrow.

HTTP Post method not working in shared hosting

In shared webhosting, the http post, put, delete not working, could you help what is the issue in code

header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With');


when i am using the get method, it is working fine
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');

Why can't we fetch all data from post and return it to read.php? To reduce the code

Why can't we get fetch all data form table and just return that data, then in while reading data just pass that data into to json_encode something like this?
In models/Post.php

        // Get Posts
    public function read() {
      // Create query
      $query = 'SELECT c.name as category_name, p.id, p.category_id, p.title, p.body, p.author, p.created_at
                                FROM ' . $this->table . ' p
                                LEFT JOIN
                                  categories c ON p.category_id = c.id
                                ORDER BY
                                  p.created_at DESC';
      
      // Prepare statement
      $stmt = $this->conn->prepare($query);

      // Execute query
      $stmt->execute();

      return $stmt;
    }

Above code to

// Get Posts
    public function read() {
      // Create query
      $query = 'SELECT c.name as category_name, p.id, p.category_id, p.title, p.body, p.author, p.created_at
                                FROM ' . $this->table . ' p
                                LEFT JOIN
                                  categories c ON p.category_id = c.id
                                ORDER BY
                                  p.created_at DESC';
      
      // Prepare statement
      $stmt = $this->conn->prepare($query);

      // Execute query
      $stmt->execute();

      return  $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

Then in api/post/read.php

$stmt = $post->read();
$count = Count($stmt);
if($count>0){
    echo json_encode( $stmt);
}
else {
    echo json_encode(
      array('message' => 'No Posts Found')
    );
}

So that we can cut short the coding right..

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.