1
Hello, I’m having trouble printing table data.
Updating: I inserted the following lines in the file php connection.:
public function select(){
$sth = $this->prepare("SELECT id_prato, titulo, descricao, preco FROM prato");
$this->execute();
$result = $sth->fetchAll();
return $result;
}
php connection.
// conexao banco de dados
<?php
class Conexao {
private $data = array();
//variavel da classe Base
protected $pdo = null;
public function __set($name, $value){
$this->data[$name] = $value;
}
public function __get($name){
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
$trace = debug_backtrace();
trigger_error(
'Undefined property via __get(): ' . $name .
' in ' . $trace[0]['file'] .
' on line ' . $trace[0]['line'],
E_USER_NOTICE);
return null;
}
//método que retorna a variável $pdo
public function getPdo() {
return $this->pdo;
}
//método construtor da classe
function __construct($pdo = null) {
$this->pdo = $pdo;
if ($this->pdo == null)
$this->conectar();
}
//método que conecta com o banco de dados
public function conectar() {
$local = "localhost";
$user = "root";
$pass = "";
$basename = "diner";
try {
$this->pdo = new PDO("mysql:host=$local;dbname=$basename",
"$user",
"$pass",
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
//método que desconecta
public function desconectar() {
$this->pdo = null;
}
public function select(){
$pdo = $this->getPdo();
$sth = $pdo->prepare("SELECT id_prato, titulo, descricao, preco FROM prato");
$sth->execute();
$result = $sth->fetchAll();
return $result;
}
}
?>
list-dish.php
//onde será imprimido os dados
<?php
//inclui as bibliotecas
require_once('conexao.php');
//faz a canexão
$pdo = new Conexao();
// determina o numero de registros que serão visualisados
$maximo = 20;
// armazenamos o valor da pagina atual
$pagina = isset($_GET['pagina']) ? ($_GET['pagina']) : '1';
// subtraimos 1, por que os registros sempre começam do 0
$inicio = $pagina - 1;
//multiplicamos a quantidade de registros pelo valor da pagina atual
$inicio = $maximo * $inicio;
$strCount = $pdo->select("SELECT COUNT(*) AS 'prato_id' FROM prato");
$total = 0;
if(count($strCount)){
foreach ($strCoun as $row) {
// armazeno total de registros da tabela para fazer paginação
$total = $row["id_prato"];
}
?>
<!DOCTYPE HTML>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width" />
<title>Paginação com PHP</title>
<link rel="stylesheet" type="text/css" href="css/estilo.css" />
<link rel="stylesheet" type="text/css" href="css/reset.css" />
</head>
<body>
<table class="tabela1">
<colgroup>
<col class="coluna1"/>
<col class="coluna2"/>
<col class="coluna3"/>
</colgroup>
<caption>Paginação com PHP</caption>
<thead>
<tr>
<th>Codigo</th>
<th>Municipio</th>
<th>UF</th>
</tr>
</thead>
<tbody>
<?php
//se a tabela nao estiver vazia, percorremos linha por linha pegando os valores
if(count($result)){
foreach ($result as $res) {
echo "<tr>";
echo " <td>".$res['titulo']."</td>";
echo " <td>".$res['descricao']."</td>";
echo " <td>".$res['preco']."</td>";
echo "</tr>";
}
}
?>
</tbody>
</table>
<div id="paginação">
<?
//determina quantos links serão adicionados e removidos
$max_links = 6;
// dados para os botões
$previous = $pagina - 1;
$next = $pagina + 1;
// usa função "ceil" para arredondar o numero
$pgs = ceil($total / $maximo);
//se a tabela nao for vazia, adicionar botões
if($pgs > 1){
echo "<br/>";
//botao anterior
if($previous > 0){
echo "<div id='botaoprox'><a href=".$_SERVER['PHP_SELF']."?pagina=$previous><input type='submit' name='bt-enviar' id='bt-enviar' value='Anterior' class='button' /></a></div>";
}else{
echo "<div id='botaoanteriorDis'><a href=".$_SERVER['PHP_SELF']."?pagina=$previous><input type='submit' name='bt-enviar' id='bt-enviar' value='Anterior' class='button' disabled='disabled'/></a></div>";
}
}
echo "div id='numpag'>";
for($i=$pagina-$max_links; $i <= $pgs-1; $i++) {
if ($i <= 0){
//enquanto for negativo, não faz nada
}else{
//senão adiciona o link para a outra página
if($i == $pgs){
//se for o final da pagina, coloca ...
echo "<a href=".$_SERVER['PHP_SELF']."?pagina=".($i).">$i</a> ...";
}
}
}
?>
</div>
</body>
</html>
Internal page where the result will be displayed internal php.:
<?php
require_once 'usuario.php';
require_once 'sessao.php';
require_once 'autenticador.php';
$aut = Autenticador::instanciar();
$usuario = null;
if ($aut->esta_logado()) {
$usuario = $aut->pegar_usuario();
}
else {
$aut->expulsar();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Pagina interna</title>
</head>
<body>
<h1>Página interna do sistema</h1>
<p>Você está logado como
<strong><?php print $usuario->getNome(); ?></strong>.
</p>
<p><a href="controle.php?acao=sair">Sair</a></p>
<?php include 'form-insert.php' ?>
<?php include 'lista-prato.php' ?>
</form>
</body>
</html>
Error (already solved in the answers):
Parse error: syntax error, Unexpected end of file in C: wamp www login lista-prato.php on line 1021
Update 2: It is returning the following error (already fixed in the comments):
( ! ) Fatal error: Call to Undefined method Connexion::prepare() in C: wamp www login connexion.php on line 58
Update 3:
Notice: Undefined variable: result in C:\wamp\www\PROJETOS\210DINER\site-definitivo\newdiner\login\lista-prato.php on line 54
Call Stack
# Time Memory Function Location
1 0.0529 245376 {main}( ) ..\interno.php:0
2 0.0597 315008 include( 'C:\wamp\www\login\lista-prato.php' ) ..\interno.php:34
Does anyone know where I am going wrong and how I should proceed? I have to create the method prepare()
? in a function
? as I did with select
? or need not prepare
, I can execute the select
at once?
Prepare
is a PDO method. On the line 58 leave it so:$sth = $this->$pdo->prepare("SELECT id_prato, titulo, descricao, preco FROM prato"); $this->$pdo->execute();
and not only$this
. Something else in the file list-dish.php you call this method so:$pdo->select("SELECT COUNT(*) AS 'prato_id0' FROM prato");
, Are you sure that’s right?– stderr
really, there was a 0 that shouldn’t. I changed the code to what you suggested.
public function select(){ 
 $sth = $this->pdo->prepare("SELECT id_prato, titulo, descricao, preco FROM prato"); 
 $this->pdo->execute(); 
 $result = $sth->fetchAll(); 
 return $result; }

If so, it was a mistake. ( ! ) Fatal error: Call to Undefined method PDO::execute() in C: wamp www login conexao.php on line 59– manzetti.denis
Ops, leave this function as: http://pastebin.com/TVnECSg3 also note that in the file list-dish.php you call the method
select
with arguments, and in php connection. she doesn’t get.– stderr
errors: ( ! ) Notice: Undefined variable: Pdo in C: wamp www login conexao.php on line 58 Notice: Undefined Property via __get(): in C: wamp www login conexao.php on line 58 in C: wamp www login conexao.php on line 21 _ Fatal error: Call to a Member Function prepare() on a non-object in C: wamp www login conexao.php on line 58
– manzetti.denis
You’re talking about COUNT ? So I got really confused..
– manzetti.denis
Note that you call it with arguments, but you do not use parameters in the function. About the error, you have a method that already returns the variable
pdo
, the functiongetPdo
use it. http://pastebin.com/kCQmHn8z– stderr
Okay, I’ve updated the question. Error returned:
( ! ) Notice: Undefined variable: resultado in C:\wamp\www\PROJETOS\210DINER\site-definitivo\newdiner\login\lista-prato.php on line 54
– manzetti.denis
This variable is not defined, it was not meant to be
strCount
?– stderr
Fine, they stopped the bugs. but it’s not printing the database data!
– manzetti.denis
I left so: http://pastebin.com/Pd0rczsK he prints: Notice: Array to string Conversion in C: wamp www PROJECTS 210DINER site-definitive newdiner login lista-prato.php on line 27 and below one of the error prints on the screen 'Array'
– manzetti.denis
Do so:
echo "<pre>" . print_r($resultados, 1) . "<pre>";
– stderr
printed: Array ( )
– manzetti.denis
Regardless of how you call the method
select
, to query who will perform will always beSELECT id_prato, titulo, descricao, preco FROM prato
which is defined in the body of the function.– stderr
Then.. it prints an empty Array, I changed in the body of the function all select of the code call the data.
("SELECT id_prato, titulo, descricao, preco FROM prato");
http://pastebin.com/K4eeQsGg– manzetti.denis