php rest-api查询返回空体

dba5bblo  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(415)

我无法让我的php restapi工作,它只是返回一个成功的http请求(200)的空主体。
当我只是呼出一些东西,它返回它很好。我使用的是slim(php微框架), MySQL , apache . 数据库表是在phpmyadmin中创建的。
索引.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();

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;
    }
}

日期.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"));

来解决问题。

5n0oy7gb

5n0oy7gb1#

若要返回json,请尝试替换

echo json_encode($dates);

具有

return $response->withJson($dates);

正如mim在评论中所建议的那样。

相关问题