rexhin
rexhin

Reputation: 449

Error getting results from MySQL database

This is my class for connecting to a database but when I create an instance of that class it gives me this error: Fatal error: Call to undefined method DB::query() in C:\Apache24\htdocs\core\DB.class.php on line 21.

 <?php

class DB {
    protected $db_name = "data_db";
    protected $db_user = "root";
    protected $db_pass = "root";
    protected $db_host = "localhost";

    public function __construct() {
        $db = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
        if ($db->connect_errno) {
            printf("Connection failed: %s\n", $db->connect_error);
            exit();
        } else
            return $db;
    }
}

$db = new DB();

$data_row = $db->query("SELECT * FROM `users`");
while($data = $data_row->fetch_assoc())
    echo $data["first_name"] . '<br>';

?>

Fatal error: Call to undefined method DB::query() in C:\Apache24\htdocs\core\DB.class.php on line 21

Upvotes: 0

Views: 60

Answers (1)

Danijel
Danijel

Reputation: 12689

Constructors don't return custom values, they return instance of the class. To test this use var_dump( $db ); and output will be object(DB) .... Save the connection as property of the object like:

public function __construct() {
    $this->mysqli = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
}

$db = new DB();
$data_row = $db->mysqli->query("SELECT * FROM `users`");

Upvotes: 2

Related Questions