I cannot get my PHP Rest API to work, it is just returning empty body with a successful HTTP request(200).
When I just echo something out it returns it fine. I am using Slim (PHP micro framework), MySQL,apache. Database table is created in phpmyadmin.
index.php
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require '../vendor/autoload.php';
require '../src/config/db.php';
$app = new \Slim\App;
$app->get('/hello/{name}', function (Request $request, Response $response) {
$name = $request->getAttribute('name');
$response->getBody()->write("Hello, $name");
return $response;
});
// Customer Routes
require '../src/routes/dates.php';
$app->run();
db.php it also contains dbhost, dbuser, dbpass and dbname variables above
<?php
class db
{
// Properties
var $dbhost = 'localhost';
var $dbuser = 'root';
var $dbpass = 'parool1';
var $dbname = 'slimapp';
// Connect
public function connect()
{
$mysql_connect_str = "mysql:host=$this->dbhost;dbname=$this->dbname";
$dbConnection = new PDO($mysql_connect_str, $this->dbuser, $this->dbpass);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbConnection;
}
}
dates.php
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
$app = new \Slim\App;
// Get All Calendar Dates
$app->get('/api/date', function (Request $request, Response $response) {
$sql = "SELECT * FROM `calendardates`";
try {
// Get DB Object
$db = new db();
// Connect
$db = $db->connect();
$stmt = $db->query($sql);
$dates = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($dates);
} catch (PDOException $e) {
echo '{"error": {"text": ' . $e->getMessage() . '}';
}
});
Change collation of database table to utf8 (if you want to use charcaters like "ö, ä, ü" in your database table).
I changed
$dbConnection = new PDO($mysql_connect_str, $this->dbuser, $this->dbpass);
to
$dbConnection = new PDO($mysql_connect_str, $this->dbuser, $this->dbpass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
to fix the problem.


var_dump($dates)outputs?return $response->withJson($dates)?