SELECT with PDO and PHP OO

Asked

Viewed 588 times

0

I am just starting my study on PHPOO, leaving more of the area of Structured... And after some studies, I obtained a part of the knowledge, but when trying to make a search in the database to verify the existence of the following user, returned me the following error.

Fatal error: Uncaught Error: Call to a Member Function prepare() on null in D: Programs xamp htdocs events.php:39 Stack trace: #0 D: Programs xamp htdocs events.php(48): Usuarios->getUsuario('daniel@servidor...', '123') #1 {main} thrown in D: 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");
?>
  • I believe the connection is invalid because the class attributes are as static and in the connection method you use $this->getHost(). I believe that it is best to leave everything static. That $cn = new Conexao(); it gets really weird.

1 answer

0


Your connection function returns nothing.

$con = $cn->connect();

Then it is assigned null 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>");
    }
}
  • Dude, you are a GOD KKKKKKKK, thank you so much bro. Another one I learned. Thanks even.

Browser other questions tagged

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