-2
Hello.
My algorithm is only returning a record from the database. I have reviewed the code several times, but I cannot understand the reason. I’m using the Slim Framework.
Follows the code:
index php.
$app->get('/ticket', function(Request $req, Response $res){
$tickets = new Ticket($this->db);
$tickets = $tickets->getTickets();
$res->getBody()->write("Todos os tickets: ");
var_dump($tickets);
$this->logger->addInfo('Busca todos os tickets');
return $res;
});
Ticket.php
require "ConDb.php";
class Ticket extends ConDb
{
private $DB;
function __construct($db)
{
parent::__construct($db);
}
function getTickets()
{
return $this->read();
}
function getTicketById($id)
{
return $this->read($id);
}
}
Condb.php
abstract class ConDb
{
private $DB;
function __construct($db)
{
$this->DB = $db;
}
function read($id = null)
{
try{
if($id != null)
{
$stmt = $this->DB->prepare("SELECT * FROM tickets WHERE id = ?");
$stmt->bindParam(1, $id, PDO::PARAM_INT);
}
else
{
$stmt = $this->DB->prepare("SELECT * FROM tickets");
}
if($stmt->execute())
{
return $stmt->fetch(PDO::FETCH_OBJ);
}
else
{
throw new PDOException("Nao foi possivel realizar a operacao.");
}
}
catch(PDOException $erro)
{
echo "Erro: ".$erro->getMessage();
}
}
}
Note that in the Condb.php file you use $stmt->fetch, to return more than one record, fetchAll is used()
– Everton Neri
Thanks Everton! That’s right. It’s just that I’m starting to learn now. Thanks!
– Mozelli