0

if plan to create database class to use it in any php project , so i write the basic class with little code below , but when test it i got error message Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\AppServ\www\cms\includes\cmsDatabase.php on line 38 Although i create connection in class constructor assigned to the local var.

My Code :

<?php
class cmsDatabase {


//Database Info 
var $db_host = "localhost";
var $db_username = "root";
var $db_password="root";
var $db_database= "mydb";

//Database Parameters 
var $database_connection ;
var     $database_db ;
var   $error_Message ;   

public function __construct(){
    $database_connection = mysqli_connect($this->db_host,$this->db_username,$this->db_password,$this->db_database) or die("can't connect to server") ;

}// end __construct  

public function __destruct(){
    mysqli_close($this->database_connection);
}// end __destruct   


function getLastError(){
    return $this->error_Message  ;
    }


//==================== DATABASE OPERATIONS ======================
function getConnection(){
        return $this->database_connection ;
}

function selectQuery ($sql){

    $result = mysqli_query($this->database_connection,$sql); //>> ERROR HERE
    return $result ;

}




}//Class 



?>
2

1 Answer 1

3

You have to use:

$this->database_connection in your constructor, otherwise its just a local variable and out of scope for your query.

Update: Oh and don't use var, it's deprecated in PHP 5: What does PHP keyword 'var' do?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.