Reputation: 413
I'm newbie on Restful API's. I'm trying to make my own following internet tutorials. For this API i'm using Slim PHP Framework.
I've create my db.php (config file):
<?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;
}
}
And then i've got my paciente.php (Where i'm trying to fetch de data to):
<?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().'}';
}
});
I'm getting this error when i try to load /api/pacientes:
Slim Application Error A website error has occurred. Sorry for the temporary inconvenience.
I've already tested the connection with the DB and it's ok. I might be doing something wrong on the config file (db.php) but idk. Thank you to everyone for reading and answering!
EDIT: Add my index.php if needed:
<?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();
Upvotes: 0
Views: 900
Reputation: 413
It was a typo: Line 18 on pacientes.php
$pacientes = $stmt->fetchAll(**PDO::FETCH_OBJECT**);
MUST BE
$pacientes = $stmt->fetchAll(***PDO::FETCH_OBJ***);
Upvotes: 1