Problem picking up data by ID in the API with Slim

Asked

Viewed 180 times

0

I’m trying to create an API with Slim to power an app, but I came across the following problem: I can get all the data from db, but I can’t get a specific data.

At the url: http://localhost/api/ which is where I get all the data, I can return a json with all the data registered, all right. But if I try with http://localhost/api/people/3 he returns me an empty json.

That’s the code I’m using:

<?php

require 'vendor/autoload.php';
require 'lib/mysql.php';
use \Slim\App;

$app = new App();

$app->get('/', 'get_peoples');

$app->get('/people/{id}', function($request, $response, $args) {
    get_people_id($args['id']);
});

$app->run();

function get_peoples() {
    $db  = connect_db();
    $sql = "SELECT * FROM peoples ORDER BY 'name'";
    $exe = $db->query($sql);
    $data = $exe->fetch_all(MYSQLI_ASSOC);
    $db = null;
    echo json_encode($data);
}

function get_people_id($people_id) {
    $db = connect_db();
    $sql = "SELECT * FROM peoples WHERE 'id' = '$people_id'";
    $exe = $db->query($sql);
    $data = $exe->fetch_all(MYSQLI_ASSOC);
    $db = null;
    echo json_encode($data);
}

?>

1 answer

0


In the get_people_id function, just remove the quotes from the id column. Type like this:

$sql = "SELECT * FROM peoples WHERE id = '$people_id'";

As it comes to be returned an empty JSON means that the syntax of the passing of parameters by the URL is correct, remaining as an error cause the SQL query.

  • Thanks, the problem was the same quotation marks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.