MySQLi can not return methods

1

I am changing my PDO application to MySQLi since I will only use SQL itself.

I create the connection in the main controller so that others can inherit 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 use in the child class:

class teste extends controller {

    function index() {

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

}

and returns this to me:

  

Fatal error: Call a member function execute () on a non-object in

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

    
asked by anonymous 17.10.2015 / 16:29

1 answer

3

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

In the openDB() method, add the fourth argument in the 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 mysqli_select_db .

    
17.10.2015 / 17:36