Source: restapi.phps - download
<?php
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* restapi.phps 0.1
* by daif alotaibi (http://daif.net)
* daif@daif.net
*
* Link:
* http://daif.net/script/restapi.phps
*
* Examples:
* $tables = [
* 'post' => ['table'=>'wp_posts', 'id'=>'ID', 'select'=>'*', 'limit'=>15, 'orderby'=>'ID', 'order'=>'ASC'],
* 'user' => ['table'=>'wp_users', 'id'=>'ID', 'select'=>'ID,user_login,user_email'],
* ];
* restapi.php?q=post
* restapi.php?q=post&orderby=id&order=ASC&&limit=30&offset=0
* restapi.php?q=post/1
*
* .htaccess file
* Options -Indexes
* <IfModule mod_rewrite.c>
* RewriteEngine On
* RewriteCond %{REQUEST_FILENAME} !-f
* RewriteCond %{REQUEST_FILENAME} !-d
* RewriteRule ^(.*)$ restapi.php?q=$1 [QSA]
* </IfModule>
*
*/
// Configurations
$config = [
// Database
'db_dsn'=> 'mysql:host=localhost;dbname=wordpress',
'db_usr'=> 'root',
'db_pwd'=> '',
'db_opt'=> [PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'"],
];
// A list of tables
$tables = [
'post' => ['table'=>'wp_posts', 'id'=>'ID', 'select'=>'*', 'limit'=>15, 'orderby'=>'ID', 'order'=>'ASC'],
'user' => ['table'=>'wp_users', 'id'=>'ID', 'select'=>'ID,user_login,user_email'],
];
// Connecting to database
$conn = new PDO($config['db_dsn'], $config['db_usr'], $config['db_pwd'], $config['db_opt']);
// set query
$query = explode('/', trim($_GET['q'],'/'));
if(isset($tables[$query[0]])){
$data = [];
$table = $tables[$query[0]] + ['select'=>'*','limit'=>'','orderby'=>'','order'=>'','orderby'=>''];
// Get table fields
$sth = $conn->prepare('SELECT '.$table['select'].' FROM `'.$table['table'].'` LIMIT 1');
$sth->execute();
$fields =array_keys($sth->fetch(PDO::FETCH_ASSOC));
// SELECT
if($_SERVER['REQUEST_METHOD'] == 'GET') {
// Set default values
$sql = 'SELECT '.$table['select'].' FROM `'.$table['table'].'`';
if(isset($_GET['orderby']) && in_array($_GET['orderby'], $fields)) {
$table['orderby'] = $_GET['orderby'];
}
if(isset($_GET['order']) && in_array(strtoupper($_GET['order']), ['ASC','DESC'])) {
$table['order'] = $_GET['order'];
}
if(isset($_GET['limit'])) {
$table['limit'] = intval($_GET['limit']);
}
if(isset($_GET['offset'])) {
$table['offset'] = intval($_GET['offset']);
}
// build SQL
if(!empty($query[1])) $sql .= ' WHERE `'.$table['id'].'`=:'.$table['id'];
if(!empty($table['orderby'])) $sql .= ' ORDER BY `'.$table['orderby'].'` '.$table['order'];
if(!empty($table['limit'])) $sql .= ' LIMIT '.$table['limit'];
if(!empty($table['offset'])) $sql .= ' OFFSET '.$table['offset'];
// SQL prepare
$sth = $conn->prepare($sql);
// SQL bind
if(!empty($query[1])){
$sth->bindValue(':'.$table['id'], $query[1]);
}
// SQL execute
if($sth->execute()) {
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
} else {
$data = ['error'=>$sth->errorInfo()];
}
}
// INSERT or UPDATE
if($_SERVER['REQUEST_METHOD'] == 'POST' || $_SERVER['REQUEST_METHOD'] == 'PUT') {
$sets = [];
// remove un-needed values from post
foreach ($_POST as $key => $value) {
if(in_array($key, $fields)) {
$sets[] = $key.'=:'.$key;
} else {
unset($_POST[$key]);
}
}
if(empty($query[1])) {
$sql = 'INSERT INTO `'.$table['table'].'` (`'.implode('`,`', array_keys($_POST)).'`) VALUES (:'.implode(',:', array_keys($_POST)).')';
} else {
$sql = 'UPDATE `'.$table['table'].'` SET '.implode(',', $sets).' WHERE `'.$table['id'].'`=:'.$table['id'];
}
$sth = $conn->prepare($sql);
foreach ($_POST as $key => $value) {
$sth->bindValue(':'.$key, $value);
}
// on update bind the id
if(!empty($query[1])) {
$sth->bindValue(':'.$table['id'], $query[1]);
}
if($sth->execute()) {
if(!empty($query[1])) {
$data = $query[1];
} else {
$data = $conn->lastInsertId();
}
} else {
$data = ['error'=>$sth->errorInfo()];
}
}
// DELETE
if($_SERVER['REQUEST_METHOD'] == 'DELETE' && !empty($query[1])) {
$sql = 'DELETE FROM `'.$table['table'].'` WHERE `'.$table['id'].'`=:'.$table['id'];
$sth = $conn->prepare($sql);
$sth->bindValue(':'.$table['id'], $query[1]);
if($sth->execute()) {
$data = true;
} else {
$data = ['error'=>$sth->errorInfo()];
}
}
} else {
$data = ['error'=>'Wrong request.'];
}
header('Content-Type: application/json');
echo json_encode($data);
?>