I'm trying to create a public REST API from scratch without using any framework and I've created where it retrieve all the data as JSON response when the user enter in this at the end of the address "...?list=all" However, I want to retrieve a row by an ID or retrieving the most popular items. I know that I will probably have to change that in the query string, but how would I create the end of the address that retrieves it? like ?ID=05 (retrieving row ID 5 from database) or TOP=15 (retrieving top popular 15). If there's a better or more efficient way to rewrite my code, feel free to let me know.
<?php
// Check Connection
if(!($db = mysqli_connect($server, $user, $password, $database))) {
die('SQL ERROR: Connection failed: '.mysqli_error($db));
exit;
}
return $db;
}
//call the passed in function
if(function_exists($_GET['list'])) {
$_GET['list']();
}
//methods
function all(){
$db = getMysqlDB();
$query = "SELECT * FROM books;";
$books_sql = mysqli_query($db, $query);
$books = array();
while($book = mysqli_fetch_array($books_sql)) {
$books[] = $book;
}
$books = json_encode($books);
echo $_GET['jsoncallback'].$books;
}
?>