How to resolve "Call to a Member Function prepare()"?

Asked

Viewed 2,072 times

1

I’m finding the following error in script down below:

Fatal error: Call to a Member Function prepare() on null in C: wamp www cursophp orientacao_object pdo_statement usuarios.php on line 20

Code:

class Usuarios {

private $db;

public function _construct(){

    try{
        $this->$db = new PDO("mysql:dbname=blog;host=localhost", "root", "");

    }catch(PDOException $e){
        echo " Falha na conexão: ".$e->getMessage();
    }

}

public function selecionar($id) {

    $sql = $this->db->prepare("SELECT * FROM usuarios WHERE id=:id");
    $sql->bindValue(":id", $id);
    $sql->execute();

    $array = array();
    if($sql->rowCount() > 0){
        $array = $sql->fetch();
    }
    return $array;
}
  • 1

    That name sounds wrong: _construct() lacks an underscore ...

1 answer

4

The constructor of a class in PHP must be named two underlines followed by the word construct. In your code there is only one underline, this does not invoke the defined constructor but the default constructor. Then it does not initialize the property $db with the PDO instance.

Change:

public function _construct(){

To:

public function __construct(){
  • Now it’s worked out. Thank you very much!

Browser other questions tagged

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