Error when using PDO: "Call a member function query () on a non-object in ..."

0

I am trying to make a query in the database, however I get the following error:

  

Fatal error: Call to a member function query () on a non-object in C: \ wamp \ www \ site-news \ Class \ Publication.class.php on line 37

I created a class publication

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();
        ?>
    
asked by anonymous 04.01.2017 / 14:50

1 answer

2

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

Wrong assignment:

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

Switch to:

$this->conn = new PDO("mysql:host={$host};dbname={$name}", $user, $pass);
    
04.01.2017 / 14:53