Undefined Variable using this

Asked

Viewed 88 times

0

I’m creating a basic class for database operations, but apache gives me two errors on line 12. Because the connection is an attribute I refer to the this. Why at the first reference when connecting to db the error is not given?

Mistakes:

Notice: Undefined variable: conexao in C:\xampp\htdocs\MinhasFuncoes\php\model.php on line 12

Fatal error: Cannot access empty property in C:\xampp\htdocs\MinhasFuncoes\php\model.php on line 12

View.php:

require_once 'model.php';
 $conn = new model("mysql","localhost", "teocratico", "utf-8","root","");
 $conn->consulta("descricao","desafios");

Model.php:

<?php
class model {
  private $conexao;
  public function __construct ($db, $host, $dbname, $charset, $usuario, $senha){
    try{
      $this->$conexao = new PDO ("$db:host=$host; dbname=$dbname; charset=$charset","$usuario","$senha");
    } catch (PDOException $erro){
        return $erro->getmessage();
    }
  }
  public function consulta ($campos, $tabela){
    $this->$conexao->prepare("SELECT :campos FROM :tabela;"); //Erro
    $this->$conexao->BindParam(':campos', $campos);
    $this->$conexao->BindParam(':tabela', $tabela);
    $this->$conexao->execute();
    $resultado = $this->$conexao->fetchAll(PDO::FETCH_ASSOC);
    echo $resultado;
  }
}
?>
  • 1

    SELECT campos FROM :tabela; take off the :fields leave as fields and ; of the end of query also.

1 answer

2


Your logic is right, however, there should be no 2 $.

Change everywhere the $this->$conexao for $this->conexao

Browser other questions tagged

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