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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
FernandoBasso
Forum Newbie
Posts: 13
Joined: Sun Dec 05, 2010 4:05 am
Location: Brazil

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

Post 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.
Last edited by FernandoBasso on Wed Dec 26, 2012 7:11 am, edited 1 time in total.
User avatar
FernandoBasso
Forum Newbie
Posts: 13
Joined: Sun Dec 05, 2010 4:05 am
Location: Brazil

Re: mysqli_query expects mysqli, object given...

Post by FernandoBasso »

I just needed some adjustment on the Test class:

Code: Select all

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