Page 1 of 1

(SOLVED) mysqli_query expects mysqli, object given...

Posted: Wed Dec 26, 2012 6:17 am
by FernandoBasso
I have the class Connection, and the class Test:

Code: Select all

<?php

require_once($root_path . '/config/db_data.php');

class Connection {

    public $db_con;

    public function __construct() {
        $this->db_connect();
    }

    private function db_connect() {

        $this->db_con = mysqli_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);
        if (!$this->db_con) {
            $error = 'Não foi possível connectar ao banco de dados. ' . mysqli_error($this->db_con);
            include_once('../views/error.html.php');
            exit();
        }
        else {
            echo '<p>Conectado ao banco.';
        }

        if (!mysqli_set_charset($this->db_con, 'utf8')) {
            $error = 'Não foi possível estabelecer o encoding da conexão. ' . mysqli_error($this->db_con);
            include_once('../views/error.html.php');
            exit();
        }
        else {
            echo '<p>Encoding da conexão estabelecido com sucesso.</p>';
        }

        if (!mysqli_select_db($this->db_con, DB_DATABASE)) {
            $error = 'Banco não encontrado. ' . mysqli_error($this->db_con);
            include_once('../views/error.html.php');
            exit();
        }
        else {
            echo '<p>Banco selecionado com sucesso.</p>';
        }

    } // Fim método 'db_connect()'.
} // Fim classe Connection.

?>

Code: Select all

<?php
class Test {
    private $db;
    public function __construct() {
        $this->db = new Connection();
        echo '<pre>'; print_r($this->db); echo '</pre>';
    }

    public function getUsers() {
        $sql = 'SELECT * FROM users;';
        $result_set = mysqli_query($this->db, $sql);
        echo '<pre>'; print_r($result_set); echo '</pre>';
    }
}
?>
And this code:

Code: Select all

$t = new Test();
$t->getUsers();
...generates the following error:


Warning: mysqli_query() expects parameter 1 to be mysqli, object given
in /home/webdev/php/sysadm/models/Test.php on line 11


Any help would be appreciated. Thanks in advance.

Re: mysqli_query expects mysqli, object given...

Posted: Wed Dec 26, 2012 7:10 am
by FernandoBasso
I just needed some adjustment on the Test class:

Code: Select all

$result_set = mysqli_query($this->db->db_con, $sql);