A
Using try/catch inside the builder no longer looks good and even more use return in it, this will not work, it is better to use try/catch out of class, because at least it will have a sensible use for them, since using a try/catch just to check the PDO and not stop the rest of what should be part of the "same" block has not much senseSo to explain better, I think the problem is occurring in the connection and how you used try/catch does not emit anything and does not end the script and how I said the return "doesn't work" __construct, then you try to use the method consultabut the variable $this->conexao did not go through try by some failure in the call new PDO, so she was still NULL.you also passed bindParam in the connection instead of using in prepare and execute:$this->conexao->prepare("SELECT :campos FROM :tabela"); //erro nessa linha
$this->conexao->BindParam(':campos', $campos);
$this->conexao->BindParam(':tabela', $tabela);
It should be this:$prepare = $this->conexao->prepare("SELECT :campos FROM :tabela"); //erro nessa linha
$prepare->BindParam(...);
$prepare->BindParam(...);
Another problem that Rray looked after me was the use of the parameters for the FROM and columns, it doesn't have how this works the way you did, the bindParam and bindValue function as character escapers, actually the parameter after processed would look like:SELECT 'id, nome, senha' FROM 'minhatabela'
Meaning query won't look minhatabela in the bank, he will look 'minhatabela' with the included apostrophes and instead of searching for 3 columns it will look generate a column with the name id, nome, senha, as if it were all one thing.I suggest changing to this:<?php
class model {
private $conexao;
public function __construct ($db, $host, $dbname, $charset, $usuario, $senha){
$this->conexao = new PDO ("$db:host=$host; dbname=$dbname; charset=$charset","$usuario","$senha");
}
public function consulta (array $campos, $tabela){
$prepare = $this->conexao->prepare("SELECT ' . $campos . ' FROM " . $tabela);
$prepare->execute();
$resultado = $prepare->fetchAll(PDO::FETCH_ASSOC);
print_r($resultado);
}
}
And on the call:require_once 'model.php';
try{
$conn = new model("mysql","localhost", "teocratico", "UTF8","root","");
$conn->consulta("descricao","desafios");
} catch (PDOException $erro){
echo $erro->getmessage();
}
Of course you should not pass access to control $campos and $tabela to the end user by GET and POST, rest use the bindParam remembering that it always "scap" the characters and "add the apostrophes" in the processing