我是Restful API的新手。我正在尝试制作自己的以下互联网教程。 对于这个API,我使用的是Slim PHP Framework。
我已经创建了db.php(配置文件):
<?php
class db {
//properties
private $dbhost = 'localhost';
private $dbuser = 'root';
private $dbpass = '';
private $dbname = 'slimapi';
//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;
}
}
然后我有我的paciente.php(我想在其中获取数据的地方):
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
$app = new \Slim\App;
//Get All Pacientes
$app->get('/api/pacientes', function (Request $request, Response $response) {
$sql = "SELECT * FROM pacientes";
try {
//GET DB Object
$db = new db();
//Connect
$db = $db->connect();
$stmt = $db->query($sql);
$pacientes = $stmt->fetchAll(PDO::FETCH_OBJECT);
$db = null;
echo json_encode($pacientes);
} catch(PDOException $e) {
echo '{"error": {"text": '.$e->getMessage().'}';
}
});
我尝试加载/ api / pacientes时遇到this错误:
Slim应用程序错误 网站发生错误。抱歉给您带来的不便。
我已经测试了与数据库的连接,没关系。我可能在配置文件(db.php)上做错了,但idk。 谢谢大家阅读和回答!
编辑: 如果需要,添加我的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, array $args) {
$name = $args['name'];
$response->getBody()->write("Hello, $name");
return $response;
});
//Pacientes Routes
require '../src/routes/pacientes.php';
$app->run();
答案 0 :(得分:1)
这是一个错字: pacientes.php上的第18行
$pacientes = $stmt->fetchAll(**PDO::FETCH_OBJECT**);
必须
$pacientes = $stmt->fetchAll(***PDO::FETCH_OBJ***);