So I am trying to create an API for my personal project to fetch data. And it is working pretty nicely until I have to select a single column.
Here in this code I am trying to add the column parameter and then take data. I am using postman to check the API and when I send request, I get the complete table no matter what.
This is my index.php file.
<?php
include 'C:xampphtdocsphpAPIsincludeFilesdatabase.php';
include 'C:xampphtdocsphpAPIsincludeFilesredirectRequest.php';
include 'C:xampphtdocsphpAPIsincludeFilesprocessRequest.php';
$method = $_SERVER["REQUEST_METHOD"];
$url = trim($_SERVER["REQUEST_URI"], "/");
$urlParts = explode("/", $url);
var_dump($urlParts);
parse_str($_SERVER['QUERY_STRING'], result: $params);
header('Content-Type: application/json');
$database = $urlParts[2]; // Default database
$table = $urlParts[3]; // Table name
$column=$urlParts[4];
$pdo = new Database("localhost", "root", "", $database);
$redirect = new RedirectRequest($pdo);
$process = new ProcessRequest($redirect);
$process->handleRequest($method, $table, $column, $params);
?>
This is the handleGet method where I am passing the parameters to select the data from database.
private function handleGet($table,$column, $params)
{
$limit = trim($params['limit'], '"') ?? 20;
$orderBy = trim($params['orderBy'], '"') ?? null;
$order = trim($params['order'], '"') ?? "ASC";
$records = $this->redirectRequest->getAll($table, $column, $limit, $orderBy, $order);
echo json_encode($records);
}
And this is the redirectRequest.php where the SQL execution takes place:
public function getAll($table, $column, $limit = 20, $orderBy = null, $order = "ASC")
{
$pdo = $this->database->getPDO();
// Prevent SQL Injection in ORDER BY
$order = strtoupper($order) === "DESC" ? "DESC" : "ASC";
$orderByClause = $orderBy ? "ORDER BY `$orderBy` $order" : "";
if($column==="all")
{
$column="*";
}
$query = "SELECT". $column ."FROM `$table` $orderByClause LIMIT :limit";
$stmt = $pdo->prepare($query);
$stmt->bindValue(":limit", (int) $limit, PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchAll();
}
This is how I passed the request in the Postman:
https://localhost/testapi-v2-test/index.php/userlist/listall/animeid
and I get data from whole table.
Here ‘userlist’ is the database ‘listall’ is the table and ‘animeid’ is the column in the table. But even if I am passing this I get complete table returned to me. And if I pass this:
https://localhost/testapi-v2-test/index.php/userlist/listall/, I do get the error for the missing parameter as this:
<br /> <b>Warning</b>: Undefined array key 4 in <b>C:xampphtdocstestAPI-V2-testindex.php</b> on line <b>16</b><br /> and then the whole table is shown too