SELECT with PDO and PHP OO

0

I'm just starting my study of PHPOO, leaving more of the Structured area ... And after some studies, I got a piece of knowledge, however when trying to search the database to check for the existence of the following user, I returned the following error.

  

Fatal error: Uncaught Error: Call to a member function prepare () on null in D: \ Program Files \ xamp \ htdocs \ events.php: 39 Stack trace: # 0 D: \ Program Files \ xamp \ htdocs \ events. php (48): Users-> getUsuario ('daniel @ server ...', '123') # 1 {main} thrown in D: \ Programs \ xamp \ htdocs \ events.php on line 39

<?php
class Conexao{
    private static $host = "localhost";
    private static $db = "esa";
    private static $user = "root";
    private static $pass = "";

    public function __construct(){}

    public function __clone(){}

    public function getHost(){return self::$host;}
    public function getDB(){return self::$db;}
    public function getUser(){return self::$user;}
    public function getPass(){return self::$pass;}

    public function connect(){
        try {
            $this->conexao = new PDO("mysql:host=".$this->getHost().";dbname=".$this->getDB()."", $this->getUser(), $this->getPass());
        }
        catch (PDOException $i)
        {
            die("Erro: <code>" . $i->getMessage() . "</code>");
        }
    }
}

class Usuarios{
    private $email;
    private $senha;

    public function __construct(){}

    public function getUsuario($email, $senha){
        $this->email = $email;
        $this->senha = md5($senha);
        $cn = new Conexao();
        $con = $cn->connect();
        $sql = $con->prepare("SELECT * FROM tb_usuarios WHERE email = :email AND senha = :senha");
        $sql->bindValue(":email", $this->email);
        $sql->bindValue(":senha", $this->senha);
        $sql->execute();
        echo $sql->rowCount();
    }
}

$user = new Usuarios();
echo $user->getUsuario("[email protected]", "123");
?>
    
asked by anonymous 28.02.2018 / 19:35

1 answer

0

Your connection function does not return anything.

$con = $cn->connect();

Then null is assigned to $con

public function connect(){
    try {
        $this->conexao = new PDO("mysql:host=".$this->getHost().";dbname=".$this->getDB()."", $this->getUser(), $this->getPass());
        // aqui você deve retornar sua conexão
        return $this->conexao;
    }
    catch (PDOException $i)
    {
        die("Erro: <code>" . $i->getMessage() . "</code>");
    }
}
    
28.02.2018 / 19:47