PDO paging - Problems with prepare (); select ();

1

Hello, I'm having trouble printing data from a table.

Update : I put the following lines in the connection.php file:

public function select(){   
  $sth = $this->prepare("SELECT id_prato, titulo, descricao, preco FROM prato");    
  $this->execute();     
  $result = $sth->fetchAll();   
  return $result; 
}

connection.php

// 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&ccedil;&atilde;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&ccedil;&atilde;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 internal.php result will be displayed:

<?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 resolved in responses):

  

Parse error: syntax error, unexpected end of file in C: \ wamp \ www \ login \ list-dish.php on line 1021

Update 2: It is returning the following error (already resolved in the comments):

  

(!) Fatal error: Call to undefined method Connection: prepare () in C: \ wamp \ www \ login \ connection.php on line 58

Update 3 :

Notice: Undefined variable: result in C:\wamp\www\PROJETOS0DINER\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 should I proceed? Do I have to create the prepare() method? in a function ? as I did with select ? or do not need prepare , can I run select at once?

    
asked by anonymous 18.05.2015 / 01:27

3 answers

3

In addition to the syntax errors in if , there is also an error in your select function:

public function select(){   
  $sth = $this->prepare("SELECT id_prato, titulo, descricao, preco FROM prato");    
  $this->execute();     
  $result = $sth->fetchAll();   
  return $result;
}

You are calling the method PDO::prepare from $this , which causes the error Call to undefined method , it is necessary to call this method from the PDO object, in your code it is returned in the getPdo() function. Therefore, the select function should look like this:

public function select($statement){
  $pdo = $this->getPdo();  
  $sth = $pdo->prepare($statement);    
  $sth->execute();    
  $result = $sth->fetchAll();  
  return $result;
}
    
18.05.2015 / 03:38
2

It's a syntax error, you said close a key in if(count($strCount)){ , change your code to:

if(count($strCount)){
    foreach ($strCoun as $row)  {
        // armazeno total de registros da tabela para fazer paginação
        $total = $row["id_prato"];
    }
}// <---- chave que faltava.
    
18.05.2015 / 01:37
2

You did not properly close this if

if(count($strCount)){
    foreach ($strCoun as $row  {
        // armazeno total de registros da tabela para fazer paginação
        $total = $row["id_prato"]
    });

should look like this:

if(count($strCount)){
    foreach ($strCoun as $row) {
        // armazeno total de registros da tabela para fazer paginação
        $total = $row["id_prato"]
    };
}
    
18.05.2015 / 01:38