0
I’m crawling in MVC and I’m picking up in a 'simple' registration. When you click on register, the errors appear:
Notice: Undefined variable: db in C: xampp htdocs cadastromvc App Models Clientemodel.php on line 9
Fatal error: Call to a Member Function prepare() on null in C: xampp htdocs cadastromvc App Models Clientemodel.php on line 9
In index.php I call config, I don’t know if the error is related to connection to the database.
Complete project if necessary: https://github.com/JonathanSilvaTI/cadastromvc
Model.php
<?php
namespace Application\Models;
class Model
{
protected $db;
public function __construct(\PDO $db){
$this->db = $db;
}
}
Clientemodel.php
<?php
namespace Application\Models;
use Application\Models\Model;
class ClienteModel extends Model
{
// Verifica se o Usuário já existe
public static function existeUsuario($usuario){
$verificaUsuario = $db->prepare("SELECT `id` FROM `loja_clientes` WHERE `usuario` = :usuario");
$verificaUsuario->bindValue(':usuario', $usuario, \PDO::PARAM_STR);
$verificaUsuario->execute();
if($verificaUsuario->rowCount() > 0){
return true;
}else{
return false;
}
}
// Verifica se o CPF já existe
public static function existeCPF($cpf){
$verificaCPF = $db->prepare("SELECT `id` FROM `loja_clientes` WHERE `cpf` = :cpf");
$verificaCPF->bindValue(':cpf', $cpf, \PDO::PARAM_STR);
$verificaCPF->execute();
if($verificaCPF->rowCount() > 0){
return true;
}else{
return false;
}
}
// Cadastro de usuário
public static function cadastrar($dados){
$sql = "INSERT INTO `loja_clientes` (nome, email, cpf, usuario, senha)
VALUES (:nome, :email, :cpf, :usuario, :senha)";
$stmt = $db->prepare($sql);
$stmt->bindValue(":nome", $dados['nome'], PDO::PARAM_STR);
$stmt->bindValue(":email", $dados['email'], PDO::PARAM_STR);
$stmt->bindValue(":cpf", $dados['cpf'], PDO::PARAM_STR);
$stmt->bindValue(":usuario", $dados['usuario'], PDO::PARAM_STR);
$stmt->bindValue(":senha", $dados['senha'], PDO::PARAM_STR);
$stmt->execute();
if($stmt){
return true;
}else{
return false;
}
}
}
Variable
$db
is not being instantiated.– Jéf Bueno
You use
static
why? and in case of access$this->db
if it’s class instances you may even have to change the way you do it! There are conceptual errors– novic