Extended PDO connection does not work

Asked

Viewed 311 times

2

The netbeans IDE does not show any errors, but when I try to run it always gives error in the browser, does anyone know what is wrong? can tell me how to use connection with father class builder method Pdo in daughter class?

Connection class:

<?php

class Conexao {

    protected $Conecta;
    private $host = "localhost";
    private $dbname = "classificados";
    private $user = "root";
    private $pass = "";

    public function __construct() {

        try {

            $this->Conecta = new PDO("mysql:host={$this->host};dbname={$this->dbname}", "{$this->user}", "{$this->pass}");
            return $this->Conecta;
        } catch (PDOException $e) {

            echo $e->getMessage();
        }
    }

}

**Classe Sessao**

    <?php

require_once "BD/Conexao.class.php";

class Sessao extends Conexao {

    private $verificaUser;

    public function setUsuario($email, $senha) {
        $this->verificaUser = parent::prepare("SELECT email, senha FROM usuarios WHERE cl_email = :email AND senha = :senha");
        $this->verificaUser->bindValue(":email", $email);
        $this->verificaUser->bindValue(":senha", $senha);
        $this->verificaUser->execute();
        return $this->verificaUser->rowCount();
    }

    public function getUsuario() {
        return $this->setUsuario();
    }

}

$teste = new Sessao;
$teste->setUsuario("[email protected]", "123");
echo $teste->getUsuario();

Error:

Fatal error: Uncaught Error: Call to undefined method Conexao::prepare() in /opt/lampp/htdocs/classificados/model/Sessao.class.php:10 Stack trace: #0 /opt/lampp/htdocs/classificados/model/Sessao.class.php(24): Sessao->setUsuario('[email protected]', '123') #1 {main} thrown in /opt/lampp/htdocs/classificados/model/Sessao.class.php on line 10

Lucas saw this and returned me this mistake:

Warning: Missing argument 1 for Sessao::setUsuario(), called in /opt/lampp/htdocs/classifieds/model/Sessao.class.php on line 18 and defined in /opt/lampp/htdocs/classifieds/model/Sessao.class.php on line 9

Warning: Missing argument 2 for Sessao::setUsuario(), called in /opt/lampp/htdocs/classifieds/model/Sessao.class.php on line 18 and defined in /opt/lampp/htdocs/classifieds/model/Sessao.class.php on line 9

Notice: Undefined variable: email in /opt/lampp/htdocs/classifieds/model/Sessao.class.php on line 11

Notice: Undefined variable: in password /opt/lampp/htdocs/classifieds/model/Sessao.class.php on line 12 0

2 answers

0

Try to leave the connection class this way; the constructor method does not return value, it is appropriate to initialize the object:

class Conexao extends PDO {

    private $host = "localhost";
    private $dbname = "classificados";
    private $user = "root";
    private $pass = "";

    public function __construct() {
        try {
            parent::__construct("mysql:host={$this->host};dbname={$this->dbname}", "{$this->user}", "{$this->pass}");
        } catch (PDOException $e) {
            echo $e->getMessage();
        }
    }

}

In the session class you will also need the instantiated connection:

<?php

require_once "BD/Conexao.class.php";

class Sessao {

    private $verificaUser;
    private $conn;

    public function __construct() {
        $this->conn = new Conexao();
    }

    public function setUsuario($email, $senha) {
        $this->verificaUser = $this->conn->prepare("SELECT email, senha FROM usuarios WHERE cl_email = :email AND senha = :senha");
        $this->verificaUser->bindValue(":email", $email);
        $this->verificaUser->bindValue(":senha", $senha);
        $this->verificaUser->execute();
        return $this->verificaUser->rowCount();
    }

    public function getUsuario() {
        return $this->setUsuario();
    }
}
  • But what PDO class am I going to extend? I don’t have that class.

  • It’s the same PHP internal PDO class you’re trying to instantiate in the constructor: $this->Conecta = new PDO(..

  • Try instantiating the connection in the constructor of the Sessao class, so it should work, as I added in the reply. I suggest you take an extra look at OO, because even if it works, this code is not yet legal; and this can give you a headache in the future if you create systems with codes like this.

0

First create your connected class by calling conexao.php

<?php

class Conexao {

public static $instance;



private function __construct() {
    //
}


public static function getInstance() {
    if (!isset(self::$instance)) {
        self::$instance = new PDO("mysql:host=localhost;port=3306;dbname=seuBanco", "root", "suasenha", array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
        self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        self::$instance->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_EMPTY_STRING);
    }
    return self::$instance;
}

Then inside another class, do the require and use the connection, like this.

 <?php

 require_once "conexao.php";

 class daoImport {



public function __construct() {

}

public function BuscarDadosCliente() {
    try {
        $linha = '';
        $sql = "SELECT * FROM SuaTabela";
        $p_sql = Conexao::getInstance->prepare($sql);
        $execute = $p_sql->execute();
        if ($execute) {
            $linha = $p_sql->fetchAll(PDO::FETCH_ASSOC);
            print_r($linha);
        } else {
            print_r($p_sql->errorInfo());
            return 'ERRO... CONTATE O SUPORTE';
        }
    } catch (Exception $ex) {
        echo "ERRRO" . $ex . "";
    }
  }

}

Browser other questions tagged

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