Error using PDO: "Call to a Member Function query() on a non-object in ..."

Asked

Viewed 1,623 times

0

I am trying to make a query in the bank, but I get the following error:

Fatal error: Call to a Member Function query() on a non-object in C: wamp www site-noticias Class Publicacao.class.php on line 37

I created a publishing class

class Publicacao {
// Atributos
public $conn;

public function __construct(){
    $this->conectar();
}

// Métodos
public function conectar() {
    try {
        // Conexao com banco MySQL
        $host = "localhost";
        $name = "noticias";
        $user = "root";
        $pass = "";
        $conn = new PDO("mysql:host={$host};dbname={$name}", $user, $pass);

        // Define para que o PDO lance exceções na ocorrência de erros
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    } catch (PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }

}

public function listarArtigos(){
    $consulta = $this->conn->query('SELECT * FROM publicacoes');
        while ($row = $consulta->fetch(PDO::FETCH_ASSOC)) {
            echo "Titulo: {$row['titulo']} <br>" . "Conteudo: {$row['conteudo']}";
        }
}
}

INDEX:

 <section class="artigo col-md-8">
        <?php
            require_once("Class/Publicacao.class.php");
            $noticia = new Publicacao;
            $noticia->listarArtigos();
        ?>

1 answer

2


The problem is the wrong assignment. Instead of assigning the connection in the property $conn it is done in a local variable of the same name.

Misconception:

$conn = new PDO("mysql:host={$host};dbname={$name}", $user, $pass);

Change to:

$this->conn = new PDO("mysql:host={$host};dbname={$name}", $user, $pass);
  • Thanks rray, it worked right !

Browser other questions tagged

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