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();
?>