Repository: bradtraversy/php_rest_myblog
Branch: master
Commit: 424976f85b3d
Files: 18
Total size: 26.0 KB
Directory structure:
gitextract_ja1r27dk/
├── .gitignore
├── README.md
├── ajaxCall.html
├── ajaxCall.js
├── api/
│ ├── category/
│ │ ├── create.php
│ │ ├── delete.php
│ │ ├── read.php
│ │ ├── read_single.php
│ │ └── update.php
│ └── post/
│ ├── create.php
│ ├── delete.php
│ ├── read.php
│ ├── read_single.php
│ └── update.php
├── config/
│ └── Database.php
├── models/
│ ├── Category.php
│ └── Post.php
└── myblog.sql
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
jtest.js
================================================
FILE: README.md
================================================
# 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](http://www.traversymedia.com)
### Version
1.0.0
### License
This project is licensed under the MIT License
================================================
FILE: ajaxCall.html
================================================
Document
Data Finder
The message will go here
Data Sender
================================================
FILE: ajaxCall.js
================================================
//POST REQUEST
$(document).ready(function(){
$('#postMessage').click(function(e){
e.preventDefault();
//serialize form data
var url = $('form').serialize();
//function to turn url to an object
function getUrlVars(url) {
var hash;
var myJson = {};
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
myJson[hash[0]] = hash[1];
}
return JSON.stringify(myJson);
}
//pass serialized data to function
var test = getUrlVars(url);
//post with ajax
$.ajax({
type:"POST",
url: "/Work folders/OOP php/RESTFUL traversy/php_rest_myblog/api/post/create.php",
data: test,
ContentType:"application/json",
success:function(){
alert('successfully posted');
},
error:function(){
alert('Could not be posted');
}
});
});
});
//GET REQUEST
document.addEventListener('DOMContentLoaded',function(){
document.getElementById('getMessage').onclick=function(){
var req;
req=new XMLHttpRequest();
req.open("GET", '/Work folders/OOP php/RESTFUL traversy/php_rest_myblog/api/post/read.php',true);
req.send();
req.onload=function(){
var json=JSON.parse(req.responseText);
//limit data called
var son = json.filter(function(val) {
return (val.id >= 4);
});
var html = "";
//loop and display data
son.forEach(function(val) {
var keys = Object.keys(val);
html += "
";
keys.forEach(function(key) {
html += "" + key + ": " + val[key] + " ";
});
html += "
";
});
//append in message class
document.getElementsByClassName('message')[0].innerHTML=html;
};
};
});
================================================
FILE: api/category/create.php
================================================
connect();
// Instantiate blog post object
$category = new Category($db);
// Get raw posted data
$data = json_decode(file_get_contents("php://input"));
$category->name = $data->name;
// Create Category
if($category->create()) {
echo json_encode(
array('message' => 'Category Created')
);
} else {
echo json_encode(
array('message' => 'Category Not Created')
);
}
================================================
FILE: api/category/delete.php
================================================
connect();
// Instantiate blog post object
$category = new Category($db);
// Get raw posted data
$data = json_decode(file_get_contents("php://input"));
// Set ID to UPDATE
$category->id = $data->id;
// Delete post
if($category->delete()) {
echo json_encode(
array('message' => 'Category deleted')
);
} else {
echo json_encode(
array('message' => 'Category not deleted')
);
}
================================================
FILE: api/category/read.php
================================================
connect();
// Instantiate category object
$category = new Category($db);
// Category read query
$result = $category->read();
// Get row count
$num = $result->rowCount();
// Check if any categories
if($num > 0) {
// Cat array
$cat_arr = array();
$cat_arr['data'] = array();
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
extract($row);
$cat_item = array(
'id' => $id,
'name' => $name
);
// Push to "data"
array_push($cat_arr['data'], $cat_item);
}
// Turn to JSON & output
echo json_encode($cat_arr);
} else {
// No Categories
echo json_encode(
array('message' => 'No Categories Found')
);
}
================================================
FILE: api/category/read_single.php
================================================
connect();
// Instantiate blog category object
$category = new Category($db);
// Get ID
$category->id = isset($_GET['id']) ? $_GET['id'] : die();
// Get post
$category->read_single();
// Create array
$category_arr = array(
'id' => $category->id,
'name' => $category->name
);
// Make JSON
print_r(json_encode($category_arr));
================================================
FILE: api/category/update.php
================================================
connect();
// Instantiate blog post object
$category = new Category($db);
// Get raw posted data
$data = json_decode(file_get_contents("php://input"));
// Set ID to UPDATE
$category->id = $data->id;
$category->name = $data->name;
// Update post
if($category->update()) {
echo json_encode(
array('message' => 'Category Updated')
);
} else {
echo json_encode(
array('message' => 'Category not updated')
);
}
================================================
FILE: api/post/create.php
================================================
connect();
// Instantiate blog post object
$post = new Post($db);
// Get raw posted data
$data = json_decode(file_get_contents("php://input"));
$post->title = $data->title;
$post->body = $data->body;
$post->author = $data->author;
$post->category_id = $data->category_id;
// Create post
if($post->create()) {
echo json_encode(
array('message' => 'Post Created')
);
} else {
echo json_encode(
array('message' => 'Post Not Created')
);
}
================================================
FILE: api/post/delete.php
================================================
connect();
// Instantiate blog post object
$post = new Post($db);
// Get raw posted data
$data = json_decode(file_get_contents("php://input"));
// Set ID to update
$post->id = $data->id;
// Delete post
if($post->delete()) {
echo json_encode(
array('message' => 'Post Deleted')
);
} else {
echo json_encode(
array('message' => 'Post Not Deleted')
);
}
================================================
FILE: api/post/read.php
================================================
connect();
// Instantiate blog 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, $post_item);
// array_push($posts_arr['data'], $post_item);
}
// Turn to JSON & output
echo json_encode($posts_arr);
} else {
// No Posts
echo json_encode(
array('message' => 'No Posts Found')
);
}
================================================
FILE: api/post/read_single.php
================================================
connect();
// Instantiate blog post object
$post = new Post($db);
// Get ID
$post->id = isset($_GET['id']) ? $_GET['id'] : die();
// Get post
$post->read_single();
// Create array
$post_arr = array(
'id' => $post->id,
'title' => $post->title,
'body' => $post->body,
'author' => $post->author,
'category_id' => $post->category_id,
'category_name' => $post->category_name
);
// Make JSON
print_r(json_encode($post_arr));
================================================
FILE: api/post/update.php
================================================
connect();
// Instantiate blog post object
$post = new Post($db);
// Get raw posted data
$data = json_decode(file_get_contents("php://input"));
// Set ID to update
$post->id = $data->id;
$post->title = $data->title;
$post->body = $data->body;
$post->author = $data->author;
$post->category_id = $data->category_id;
// Update post
if($post->update()) {
echo json_encode(
array('message' => 'Post Updated')
);
} else {
echo json_encode(
array('message' => 'Post Not Updated')
);
}
================================================
FILE: config/Database.php
================================================
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;
}
}
================================================
FILE: models/Category.php
================================================
conn = $db;
}
// Get categories
public function read() {
// Create query
$query = 'SELECT
id,
name,
created_at
FROM
' . $this->table . '
ORDER BY
created_at DESC';
// Prepare statement
$stmt = $this->conn->prepare($query);
// Execute query
$stmt->execute();
return $stmt;
}
// Get Single Category
public function read_single(){
// Create query
$query = 'SELECT
id,
name
FROM
' . $this->table . '
WHERE id = ?
LIMIT 0,1';
//Prepare statement
$stmt = $this->conn->prepare($query);
// Bind ID
$stmt->bindParam(1, $this->id);
// Execute query
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// set properties
$this->id = $row['id'];
$this->name = $row['name'];
}
// Create Category
public function create() {
// Create Query
$query = 'INSERT INTO ' .
$this->table . '
SET
name = :name';
// Prepare Statement
$stmt = $this->conn->prepare($query);
// Clean data
$this->name = htmlspecialchars(strip_tags($this->name));
// Bind data
$stmt-> bindParam(':name', $this->name);
// Execute query
if($stmt->execute()) {
return true;
}
// Print error if something goes wrong
printf("Error: $s.\n", $stmt->error);
return false;
}
// Update Category
public function update() {
// Create Query
$query = 'UPDATE ' .
$this->table . '
SET
name = :name
WHERE
id = :id';
// Prepare Statement
$stmt = $this->conn->prepare($query);
// Clean data
$this->name = htmlspecialchars(strip_tags($this->name));
$this->id = htmlspecialchars(strip_tags($this->id));
// Bind data
$stmt-> bindParam(':name', $this->name);
$stmt-> bindParam(':id', $this->id);
// Execute query
if($stmt->execute()) {
return true;
}
// Print error if something goes wrong
printf("Error: $s.\n", $stmt->error);
return false;
}
// Delete Category
public function delete() {
// Create query
$query = 'DELETE FROM ' . $this->table . ' WHERE id = :id';
// Prepare Statement
$stmt = $this->conn->prepare($query);
// clean data
$this->id = htmlspecialchars(strip_tags($this->id));
// Bind Data
$stmt-> bindParam(':id', $this->id);
// Execute query
if($stmt->execute()) {
return true;
}
// Print error if something goes wrong
printf("Error: $s.\n", $stmt->error);
return false;
}
}
================================================
FILE: models/Post.php
================================================
conn = $db;
}
// 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;
}
// Get Single Post
public function read_single() {
// 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
WHERE
p.id = ?
LIMIT 0,1';
// Prepare statement
$stmt = $this->conn->prepare($query);
// Bind ID
$stmt->bindParam(1, $this->id);
// Execute query
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// Set properties
$this->title = $row['title'];
$this->body = $row['body'];
$this->author = $row['author'];
$this->category_id = $row['category_id'];
$this->category_name = $row['category_name'];
}
// Create Post
public function create() {
// Create query
$query = 'INSERT INTO ' . $this->table . ' SET title = :title, body = :body, author = :author, category_id = :category_id';
// Prepare statement
$stmt = $this->conn->prepare($query);
// Clean data
$this->title = htmlspecialchars(strip_tags($this->title));
$this->body = htmlspecialchars(strip_tags($this->body));
$this->author = htmlspecialchars(strip_tags($this->author));
$this->category_id = htmlspecialchars(strip_tags($this->category_id));
// Bind data
$stmt->bindParam(':title', $this->title);
$stmt->bindParam(':body', $this->body);
$stmt->bindParam(':author', $this->author);
$stmt->bindParam(':category_id', $this->category_id);
// Execute query
if($stmt->execute()) {
return true;
}
// Print error if something goes wrong
printf("Error: %s.\n", $stmt->error);
return false;
}
// Update Post
public function update() {
// Create query
$query = 'UPDATE ' . $this->table . '
SET title = :title, body = :body, author = :author, category_id = :category_id
WHERE id = :id';
// Prepare statement
$stmt = $this->conn->prepare($query);
// Clean data
$this->title = htmlspecialchars(strip_tags($this->title));
$this->body = htmlspecialchars(strip_tags($this->body));
$this->author = htmlspecialchars(strip_tags($this->author));
$this->category_id = htmlspecialchars(strip_tags($this->category_id));
$this->id = htmlspecialchars(strip_tags($this->id));
// Bind data
$stmt->bindParam(':title', $this->title);
$stmt->bindParam(':body', $this->body);
$stmt->bindParam(':author', $this->author);
$stmt->bindParam(':category_id', $this->category_id);
$stmt->bindParam(':id', $this->id);
// Execute query
if($stmt->execute()) {
return true;
}
// Print error if something goes wrong
printf("Error: %s.\n", $stmt->error);
return false;
}
// Delete Post
public function delete() {
// Create query
$query = 'DELETE FROM ' . $this->table . ' WHERE id = :id';
// Prepare statement
$stmt = $this->conn->prepare($query);
// Clean data
$this->id = htmlspecialchars(strip_tags($this->id));
// Bind data
$stmt->bindParam(':id', $this->id);
// Execute query
if($stmt->execute()) {
return true;
}
// Print error if something goes wrong
printf("Error: %s.\n", $stmt->error);
return false;
}
}
================================================
FILE: myblog.sql
================================================
CREATE TABLE `categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
);
INSERT INTO `categories` (`id`, `name`) VALUES
(1, 'Technology'),
(2, 'Gaming'),
(3, 'Auto'),
(4, 'Entertainment'),
(5, 'Books');
CREATE TABLE `posts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`category_id` int(11) NOT NULL,
`title` varchar(255) NOT NULL,
`body` text NOT NULL,
`author` varchar(255) NOT NULL,
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
);
INSERT INTO `posts` (`id`, `category_id`, `title`, `body`, `author`) VALUES
(1, 1, 'Technology Post One', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut interdum est nec lorem mattis interdum. Cras augue est, interdum eu consectetur et, faucibus vel turpis. Etiam pulvinar, enim quis elementum iaculis, tortor sapien eleifend eros, vitae rutrum augue quam sed leo. Vivamus fringilla, diam sit amet vestibulum vulputate, urna risus hendrerit arcu, vitae fringilla odio justo vulputate neque. Nulla a massa sed est vehicula rhoncus sit amet quis libero. Integer euismod est quis turpis hendrerit, in feugiat mauris laoreet. Vivamus nec laoreet neque. Cras condimentum aliquam nunc nec maximus. Cras facilisis eros quis leo euismod pharetra sed cursus orci.','Sam Smith'),
(2, 2, 'Gaming Post One', 'Adipiscing elit. Ut interdum est nec lorem mattis interdum. Cras augue est, interdum eu consectetur et, faucibus vel turpis. Etiam pulvinar, enim quis elementum iaculis, tortor sapien eleifend eros, vitae rutrum augue quam sed leo. Vivamus fringilla, diam sit amet vestibulum vulputate, urna risus hendrerit arcu, vitae fringilla odio justo vulputate neque. Nulla a massa sed est vehicula rhoncus sit amet quis libero. Integer euismod est quis turpis hendrerit, in feugiat mauris laoreet. Vivamus nec laoreet neque.','Kevin Williams'),
(3, 1, 'Technology Post Two', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut interdum est nec lorem mattis interdum. Cras augue est, interdum eu consectetur et, faucibus vel turpis. Etiam pulvinar, enim quis elementum iaculis, tortor sapien eleifend eros, vitae rutrum augue quam sed leo. Vivamus fringilla, diam sit amet vestibulum vulputate, urna risus hendrerit arcu, vitae fringilla odio justo vulputate neque. Nulla a massa sed est vehicula rhoncus sit amet quis libero. Integer euismod est quis turpis hendrerit, in feugiat mauris laoreet. Vivamus nec laoreet neque. Cras condimentum aliquam nunc nec maximus. Cras facilisis eros quis leo euismod pharetra sed cursus orci.','Sam Smith'),
(4, 4, 'Entertainment Post One', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut interdum est nec lorem mattis interdum. Cras augue est, interdum eu consectetur et, faucibus vel turpis. Etiam pulvinar, enim quis elementum iaculis, tortor sapien eleifend eros, vitae rutrum augue quam sed leo. Vivamus fringilla, diam sit amet vestibulum vulputate, urna risus hendrerit arcu, vitae fringilla odio justo vulputate neque. Nulla a massa sed est vehicula rhoncus sit amet quis libero. Integer euismod est quis turpis hendrerit, in feugiat mauris laoreet. Vivamus nec laoreet neque. Cras condimentum aliquam nunc nec maximus. Cras facilisis eros quis leo euismod pharetra sed cursus orci.','Mary Jackson'),
(5, 4, 'Entertainment Post Two', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut interdum est nec lorem mattis interdum. Cras augue est, interdum eu consectetur et, faucibus vel turpis. Etiam pulvinar, enim quis elementum iaculis, tortor sapien eleifend eros, vitae rutrum augue quam sed leo. Vivamus fringilla, diam sit amet vestibulum vulputate, urna risus hendrerit arcu, vitae fringilla odio justo vulputate neque. Nulla a massa sed est vehicula rhoncus sit amet quis libero. Integer euismod est quis turpis hendrerit, in feugiat mauris laoreet. Vivamus nec laoreet neque. Cras condimentum aliquam nunc nec maximus. Cras facilisis eros quis leo euismod pharetra sed cursus orci.','Mary Jackson'),
(6, 1, 'Technology Post Three', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut interdum est nec lorem mattis interdum. Cras augue est, interdum eu consectetur et, faucibus vel turpis. Etiam pulvinar, enim quis elementum iaculis, tortor sapien eleifend eros, vitae rutrum augue quam sed leo. Vivamus fringilla, diam sit amet vestibulum vulputate, urna risus hendrerit arcu, vitae fringilla odio justo vulputate neque. Nulla a massa sed est vehicula rhoncus sit amet quis libero. Integer euismod est quis turpis hendrerit, in feugiat mauris laoreet. Vivamus nec laoreet neque. Cras condimentum aliquam nunc nec maximus. Cras facilisis eros quis leo euismod pharetra sed cursus orci.','Sam Smith');