How to set the db variable in the Clientemodel?

Asked

Viewed 85 times

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.

  • 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

1 answer

2

To access protected $db from its base class remove static of the class methods ClienteModel and make access with $this->db:

<?php
    namespace Application\Models;

    class Model
    {
        protected $db;

        public function __construct(\PDO $db){
            $this->db = $db;
        }
    }

Don’t forget to create the builder in ClienteModel passing the value of PDO and always access with $this->db in which your code is only $db.

class ClienteModel extends Model
{
    public function __construct(\PDO $db)
    {
        parent::__construct($db);
    }

    // Verifica se o Usuário já existe
    public function existeUsuario($usuario)
    {
        $sql = "SELECT `id` FROM `loja_clientes` WHERE `usuario` = :usuario";
        $verificaUsuario = $this->db->prepare($sql);
        $verificaUsuario->bindValue(':usuario', $usuario, \PDO::PARAM_STR);
        $verificaUsuario->execute();
        if($verificaUsuario->rowCount() > 0){
            return true;
        }else{
            return false;
        }
    }

Work in this case with instances:

$db = new PDO('mysql:host=127.0.0.1;port=3306;dbname=BANCO;charset=UTF8;',
        'root',
        'password');
$clienteModel = new ClienteModel($db);

This code reflects the problems encountered in your question, of course this can be further improved, but, I have just cleared up your problem.

  • I think I’m forgetting something. Error informs: Fatal error: Using $this when not in Object context - when accessing with $this->db-prepare()

  • @Jonathansilva you removed static of the methods, example: public function existeUsuario($usuario)

  • yes, even so, I came across this mistake

  • $this->db->prepare() try so missed an arrow, is typing error or did not load the PDO class

  • I was wrong to type here, but this OK in the code

  • or did not load the PDO class

  • did not understand, in Clientemodel I created builder, as you had suggested

Show 3 more comments

Browser other questions tagged

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