Database as JSON

Hello all, im new at Slim4 and i need some help. I wrote a script with Slim4 and a Database-Connection. Now i want to get the datas as json. But i didnt get it. Can someone help me? My script looks like:

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
$app = AppFactory::create();
    //Fächer auslesen
    $app->get('/ReadAPI/faecher', function (Request $request, Response $response) {
    $sql = "SELECT * FROM faecher";
        //Get DB Object
        $db = new db();
        //Verbindung herstellen
        $db = $db->connect();
        $stmt = $db->query($sql);   
        $faecher = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
            ->withHeader('content-type', 'application/json')
    catch (PDOException $e) 
        echo '{"error": {"text": '.$e->getMessage().'}';

And i get an error:

Fatal error: Uncaught TypeError: fwrite() expects parameter 2 to be string, bool given in

Thank you for your help!

The json_encode function returns false on failure.

Change the result set to array first:

$faecher = $stmt->fetchAll(PDO::FETCH_ASSOC);

Then try adding the JSON_THROW_ON_ERROR as the second parameter to see what is wrong with the database result set.

$response->getBody()->write(json_encode($faecher, JSON_THROW_ON_ERROR)):

Then change the return statement to this:

return $response
    ->withHeader('Content-Type', 'application/json')

Optional: Change the catch block to prevent JSON syntax errors:

    catch (\Exception $e) 
                    'error' => [
                        'message' => $e->getMessage(),

        return $response
            ->withHeader('Content-Type', 'application/json')

Thank you for your help!

Now i get this error:


There was a typo. It should be 'message' => $e->getMessage(),