This is a simple PHP REST API from scratch with no framework.
Import the myblog.sql file, change the params in the config/Database.php file to your own
Brad Traversy Traversy Media
1.0.0
This project is licensed under the MIT License
This is a simple PHP REST API from scratch with no framework.
Import the myblog.sql file, change the params in the config/Database.php file to your own
Brad Traversy Traversy Media
1.0.0
This project is licensed under the MIT License
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
{"message":"Post Created"}
what is the function to check Access Method?
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
I noticed that when I removed the Ajax files (html and js) from the server folder, the API still works. Also, the Youtube video does not cover their significance. Does any one know their use to the project?
php_rest_myblog/api/post/create.php
Line 19 in acc9a25
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?
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 -
PHP extension: mysqliDocumentation curlDocumentation mbstringDocumentation
PHP version: 7.3.5
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 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.
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 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..
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.