Doubt: Connection and query with PHP, PDO and MYSQL

Asked

Viewed 478 times

0

Good afternoon! I have a mistake I can’t identify at all. I need to perform more than one query in different classes on a screen. My problem is happening when the second query is run Php is returning, Call to a Member Function prepare() on null why the connection parameter that is in __Construct is returning null in the second class (I picked it up through a var_dump) why prepare it and consequently the query does not work.

I wanted to know what I am doing wrong so I could not query more than one class on the same screen. I am using PDO and mysql database.

That’s my kind of connection

<?php
// Classe que realiza a conexão com o banco de dados
Class Conexao {

    private static $con;

    // Impede que a classe seja instanciada
    private function __construct() { }

    // Impede que a classe seja  clonada
    private function __clone() { }

    //Impede a utilização do Unserialize (que a variavel retorne o array original)
    private function __wakeup() { }


    public static function getConexao() {
        if (!isset(self::$con)) {
            try{ 
               // parametros de conexão
               $tipo = 'mysql:host=localhost;dbname=teste';
               $user = 'root';
               $senha = '';


            self::$con = new PDO( $tipo, $user, $senha, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8", PDO::ATTR_PERSISTENT => TRUE));
            self::$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            self::$con->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_EMPTY_STRING);


        } 
          catch ( PDOException $erro ){
                 echo $erro;
                 // Encerrando a aplicação
                 exit();
             }
          return self::$con;
    }

  }    // finalizando o getConexao  



   protected function closeConexao() {
      if($this->con != null) $this->con = null;
    }

    public function __destruct() {
      $this->closeConexao();
    } 


} // finalizando a classe conexão

?>

This is the class in which I perform the first consultation

<?php

// ARQUIVO DE CLASSE SLIDE_CRUD - UTILIZADA PARA ADICIONAR AS IMAGENS E CONSULTAS ATRAVÉS DO LOGIN NO PAINEL-ADMIN

// chamando o arquivo de conexão

class Slide_crud extends Slide{

    public static $conexaoPDO;
    // Instanciando a conexao  e a classe
    public function __construct(){


    $this->conexaopdo = conexao::getConexao();   

    }    

//******************************************************************************************************//
//*********************************************CONSULTA GERAL******************************************//
//****************************************************************************************************// 


public function consultaslide(){
    try{

    // realizando o SQL
    $sql = ('SELECT * FROM tbl_slide');

    // Realizando a conexão

    $prepare_sql = $this->conexaopdo->prepare($sql);

    $prepare_sql->execute();

    return $prepare_sql->fetchAll(PDO::FETCH_OBJ);

    } catch(exception $e){
    echo" $e erro ao realizar a consulta, se o problema persistir contate o administrador do sistema";

    }


}

}

This is the class in which I perform the 2nd consultation.

<?php

    // Criando a Classe Seo_Crud - Classe responsável pelas interações com o banco de DADOS


Class Seo_crud extends Seo{


    // parametro na qual será responsável por iniciar a conexão com o banco de dados
    static $conexaoPDO;  

    // função responsável por instanciar a classe em questão
    public function __construct(){

     // instanciando o parametro de conexão;
    $this->conexaopdo = Conexao::getConexao(); 
    }

//******************************************************************************************************//
//********************************************CONSULTA GERAL*******************************************//
//****************************************************************************************************//

public function consultaseo(){
 try{
         // consulta SQL
         $sql = ('SELECT * FROM tbl_seo');

         // repassando a consulta para a conexão

         $prepare_sql = $this->conexaopdo->prepare($sql);

         // executando a instrução
         $prepare_sql->execute();

         // retorno da função
         return $prepare_sql->fetchAll(PDO::FETCH_OBJ);


    }catch(PDOexception $e){
            print_r($e);
            echo"$e Atenção! Ocorreu um Erro ao realizar essa consulta de dados, tente novamente, se o problema persisitir contate o Administrador do Sistema";
            }


    } // fim function consulta

}
?>

here are the snippets in which I am instantiating the classes in the index.php file to get the data through a foreach.

            // instanciando a classe responsável pelo Crud e pelas Consultas
            $slide_crud = new Slide_crud();

            // repassando os parâmetros para a consulta e armazenando na variavel $result
            $result = $slide_crud->consultaslide();

            // percorrendo o array através de um laço para exibir as imagens
            foreach($result as $dados){
            ?>     
             <div class="cycle-anterior" <a href="#" id="anterior"></a></div>
            <div class="cycle-proximo" <a href="#" id="proximo"></a></div>
            <img src="<?=$dados->caminho ?>" class="img-thumbnail" height="260" width="960" data-cycle-desc= <?=$dados->descricao?>>
            <?php

            }




<?php 

   // instanciando a classe responsável pela consulta;
   $seo_crud = new Seo_crud();
  // realizando a consulta e armazenando os dados em uma variavel
   $result_seo = $seo_crud->consultaseo();

   if(!Empty($result_seo)){
        foreach($result_seo as $dados){
       echo "$dados->rodape_centro";
        }
   }

?>     
  • It is not the same question as this: https://answall.com/questions/200922/php-segunda-query-retorna-null?

  • In the connection class you use a static field for connection but when closing the connection you call an attribute of the class instance. Why the connection attribute is static?

  • the connection is static by the Singleton standard... and the error was this! when closing the connection was calling the attribute wrongly where it should be.. self::$con so that the query was not performed because the connection did not close and the other class could not identify the new connection because of the if(! isset(self::con) in connection class.. problem solved

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.