View Full Version : Issues with classes: mysqli_query() expects parameter 1 to be mysqli, null given

01-03-2012, 04:49 PM
Hello everyone!

I am having trouble the last few days trying to output data from my database. This is concerning using the "mysqli_connect" and "mysqli_query" parameters.

What I have done is I want to put the connection settings in a class, and I with the normal "mysql_connect" it does work. But with mysqli it doesn't work.

What I get is an error message saying: "Warning: mysqli_query() expects parameter 1 to be mysqli, null given". Is there anything I am doing wrong here?

class database_connect {
var $db_host;
var $db_user;
var $db_pass;
var $db_db;
function connect() {
$connect_db = mysqli_connect($this->db_host, $this->db_user, $this->db_pass, $this->db_db) or die ("Connection failed");
function close() {

$db_countries = new database_connect;
$db_countries->db_host = "localhost";
$db_countries->db_user = "root";
$db_countries->db_pass = "";
$db_countries->db_db = "site_countries";

function dbconnect_countries() {
global $db_countries, $connect_db;
$query = "SELECT * FROM countries";
$result = mysqli_query($connect_db, $query) or die ("Error in query: $query. ".mysqli_error());
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_row($result)) {
echo '<div>'.$row[0].'</div>';
else {
echo '<div>No countries found!</div>';

Any help would be appreciated!


01-03-2012, 05:54 PM
You're not really displaying an understanding of variable scope. You should avoid trying to global scope variables and connection pointers. You also don't seem to understand how classes work. You know you can use mysqli as an object itself?

When you call a new instance of a class, the object will call the construct() magic method. I would use this to connect to the database, or at least set the connection parameters (although an immediate connection avoids actually storing the values). I would then store the connection pointer in a property of the class. The class should also store methods to act on the connection.

Classes and objects are used to handle specific areas - separating logic into classes that deal with similar tasks. Therefore, a database class should be built to contain all the tools to access the database.

How I would build your database class:

class database {

private $connection = '';

protected function __construct($host, $db_user, $db_pass, $database){
$this->connection = mysqli_connect($host, $db_user, $db_pass, $database);
throw new Exception('Connect failed: '.mysqli_error());

protected function query($query){
// Could probably throw an exception here as well, if result was false
return mysqli_query($this->connection, $query);

protected __destruct(){

Google some database class examples - the php.net manual has a great explanation of PHP class definitions.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum