Error trying to select with PHPOO

Asked

Viewed 98 times

1

Well, I’m a beginner in PHPOO and I developed a class with functions to connect to the database (already successful) and another to select (where the error occurs). I will post the code and then report the error.

index php.:

<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
    require_once("class/Banco.class.php");

    $banco = new Banco("localhost", "phpoo", "root", "");

    $banco->Select();
}
?>

<!DOCTYPE html>
<html lang="pt-BR">
    <head>
        <meta charset="UTF-8">
        <title>Login com PHPOO</title>
    </head>

    <body>
        <form action="" method="POST">
            <input type="text" name="usuario" placeholder="Usuario">
            <input type="password" name="senha" placeholder="Senha">

            <input type="submit" value="Logar!">
        </form>
    </body>
</html>

Banco.class.php:

<?php
class Banco {
    protected $host;
    protected $bd;
    protected $usuario;
    protected $senha;

    public function __construct($host, $bd, $usuario, $senha) {
        $this->host = $host;
        $this->bd = $bd;
        $this->usuario = $usuario;
        $this->senha = $senha;

        try {
            $conexao = new PDO("mysql:host=".$this->host.";dbname=".$this->bd."", $this->usuario, $this->senha,
                array(
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, 
                    PDO::ATTR_PERSISTENT => false,
                    PDO::ATTR_EMULATE_PREPARES => false,
                    PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
                )
            );
        } catch(PDOException $e) {
            echo "Ocorreu um erro: ".$e->getMessage();
        }
    }

    public function Select() {
        $listarUsuarios = $conexao->prepare("SELECT * FROM usuarios ORDER BY id DESC");
        $listarUsuarios->execute();

        $linhaUsuario = $listarUsuarios->fetchAll(PDO::FETCH_ASSOC);
        $contaUsuario = $listarUsuarios->rowCount();

        if($contaUsuario) {
            echo "Tem usuario: ".$contaUsuario;
        } else {
            echo "Nao tem usuario: ".$contaUsuario;
        }
    }
}
?>

When trying to log in, the following error appears:

Notice: Undefined variable: conexao in C:\xampp\htdocs\PHPOO\class\Banco.class.php on line 29

Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\PHPOO\class\Banco.class.php on line 29

As I mentioned earlier, I am a beginner in PHPOO, so how can I solve both errors? And the way I’m making the connection is correct and secure?

Thank you!

1 answer

1


The error is saying: Your $connected variable does not exist. You have prompted it in the constructor, but in the select method it does not exist. You can do the following:

In the class declaration:

protected $conexao;

In the builder:

$this->conexao = new PDO("mysql:host=".$this->host.";dbname=".$this->bd."", $this->usuario, $this->senha,
            array(
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, 
                PDO::ATTR_PERSISTENT => false,
                PDO::ATTR_EMULATE_PREPARES => false,
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
            )
        );

In the Select method:

$listarUsuarios = $this->conexao->prepare("SELECT * FROM usuarios ORDER BY id DESC");

As for the way and security to connect, it is to say that it is correct and relatively safe. Others can contribute more to this.

I hope I helped.

[]s

  • Hello, first thank you for answering. So I made exactly the modifications you suggested and the same mistakes continue. In relation to the Select method $this->listUsuarios is correct, and listUsuarios is not registered in the class declaration and is only a single variable?

  • Sorry @Igor, my fault. I had not tested the code and had put $this in the wrong variable. See now fixed, is $listarUsuarios = $this->conexao

  • Understanding the basics of OO: when you access for ->$var you are reading an attribute of the class, which is instantiated within all methods, already the access of variables by $var, or you need to set it within the method or inject as Function parameter, ex.: public function($var) {}

  • Thanks, now it worked! I had already made this modification but it hadn’t worked I don’t know why. Thank you very much!

Browser other questions tagged

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