Я не могу заставить свой PHP Rest API работать, он просто возвращает пустое тело с успешным HTTP-запросом (200).
Когда я просто отгоняю что-то, это возвращает его. Я использую Slim (PHP micro framework), MySQL
, apache
. Таблица базы данных создается в 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 также содержит параметры dbhost, dbuser, dbpass и dbname выше
<?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() . '}';
}
});
Решение:
Измените сопоставление таблицы базы данных с utf8 (если вы хотите использовать в таблице базы данных такие символы, как "ö, ä, ü").
Я изменился
$dbConnection = new PDO($mysql_connect_str, $this->dbuser, $this->dbpass);
в
$dbConnection = new PDO($mysql_connect_str, $this->dbuser, $this->dbpass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
решить проблему.
Чтобы вернуть json, попробуйте заменить
echo json_encode($dates);
С
return $response->withJson($dates);
Как было сказано в комментариях.
var_dump($dates)
?return $response->withJson($dates)
?