Mysqli cannot return methods

Asked

Viewed 52 times

2

I am changing my PDO application to Mysqli since I will only use SQL even.

I create the connection on the main controller so others can open it:

class Controller {

    function __construct() {

    }

    public function openDB() {

        //$options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING);
        $this -> db = new mysqli(DB_HOST, DB_USER, DB_PASS);

        if ($this -> db -> connect_errno) {
            die("Failed to connect to MySQL: " . $this -> db -> connect_error);
        } else {
        return $this -> db;
        }

    }
}

An example of use in the daughter class:

class teste extends controller {

    function index() {

        $db = $this -> openDB();
        $stmt = $db->prepare("SELECT * FROM teste WHERE id = 1");
        $stmt->execute();
    }

}

and this comes back to me:

Fatal error: Call to a Member Function execute() on a non-object in

i give a var_dump in the variable $db to test if the connection is OK and it returns me a normal array...

  • The only night was the lack of selecting the database and data.

  • Damn, how did I not see that? and gave no error rsrs, Thank you!

  • Do not select the bank not from the same error.

  • @rray put as answer

1 answer

3


The error happens because no database was selected, so the prepare() failed and does not return an object.

In the method openDB(), add fourth argument in mysqli constructor

$this -> db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

If you need to change banks during the application you can use the function mysqli_select_db.

Browser other questions tagged

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