I'm setting up a REST service using Slim Framework and PDO. I've a controller with optional parameters for GET request, in particular, user can set fields to be selected and results limit value:
/*
GET /products
{fields} -
{limit} -
*/
$app->get(
'/products(/)', function () use ($app, $dbHelper) {
$app->response()->header("Content-Type", "application/json");
$params = $app->request->get();
echo json_encode($dbHelper->getProducts($params));
}
);
Writing down "getProducts" method I need to check for that parameters and to build a prepared statement for the query:
function getProduct($id, $params) {
if(isset($params['fields'])) {
$fields = $params['fields'];
} else {
$fields = "id, name, price";
}
if(isset($params['limit'])) {
$limit = $params['limit']);
} else {
$limit = 30;
}
try {
$sqlProduct = "SELECT :fields";
$sqlProduct.= " FROM products";
$sqlProduct.= " LIMIT :limit";
$stmt = $this->db->prepare($sqlProduct);
$stmt->bindValue(':fields', $fields, PDO::PARAM_STR); // is this a String?
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->execute();
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($products as $product) {
array_push($this->response, $product);
}
} catch (PDOException $pdoe) {
echo "PDOException: " . pdoe.getMessage();
}
return $this->response;
}
I'm PDO newbie, the code above is not working correctly. What is the correct way to parametrize the query?
Shuld I use isset function to check for params?
What about data type check (e.g. how can I be sure that "limit" is a number)?