Method get always returns the same


#1

Hello, I’m new to this slim framework, I have a problem, I have a developed api but no framework before and I’m developing the whole api with the help of slim 3, everything is fine but when I make calls through “GET” The api always returns the same, I explain it is supposed to connect to the database and returns different results but once I call the first time I get the same result, this is always with everything. The only way I get back another result is to reload the page with f5 control. It is as if you saved what will return me in the cache.
This is my code

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require 'vendor/autoload.php';
require 'library/Connection.php';

$conn = null;

$app = new \Slim\App([
    'settings' => [
        'displayErrorDetails' => true
    ]
        ]);


$app->get('/messages/{id}',	'getMessage');

$app->run();



function getMessage(Request $request, Response $response, $args) {

    //   $name = $request->getAttribute('name');
    $id = $args['id'];
    $sql = "SELECT * FROM messages WHERE user1='$id'";
    
    try {

        $db = getConnection();

        $stmt = $db->query($sql);

        $users = $stmt->fetchAll(PDO::FETCH_OBJ);

        $db = null;

        $response->getBody()->write('{"users": ' . json_encode($users) . '}');
    } catch (PDOException $e) {

        $response->getBody()->write('{"error":{"text":' . $e->getMessage() . '}}');
    }



    return $response;
}



function getConnection() {

    global $conn;

    if (is_null($conn)) {

        $conn = new Connection();
    }

    return $conn->getConnection();
}

#2

Perhaps something like this:

$app->get('/messages/{id}', function (Request $request, Response $response, $id) 
{
	return getMessage($request, $response, $args);
}

And you can always debug and see what id is in your case.

Better is, to separate routing logic more like in a MVC pattern.
the route is calling a controller. (MessageController)
the controller calls the underlying database model MessageModel)
and renders that with the view (probably a twig template), or a json response