1 post
  • Has been part of the Envato Community for over 2 years
gutigrewal says

Hi all, Im trying to learn Object Oriented PHP but I’m having some difficulty. I have a database class which goes as follows:

<?php
       class database {
           public $dbHost = 'localhost';
           public $dbUser = 'root';
            public $dbPass = '';
           public $dbName = 'undergradpad';
            public $mysqli;

public function __construct(){
    }

public function dbConnect(){
    ### not $mysqli
    $this->mysqli = new mysqli($this->dbHost, $this->dbUser, $this->dbPass, $this->dbName);
$this->mysqli->select_db('undergradpad'); 
    /* check connection */
    if (mysqli_connect_errno()){
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }else{
        echo 'connection made';
    }
    /* close connection */
    ### $this->db->close(); // DO NOT close the connection here!
}

       public function __destruct(){
        $this->mysqli->close();
        }

           }
           ?> 
This works fine the database connection is made, however I get this error when running a query:
 Fatal error: Call to a member function query() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/undergradpad2/house.class.php on line 19 
Here is the class I have made in relation:
<?php
class house {
        function __construct() {
            include('database.php');
            $mysqli = new database();
$mysqli->dbConnect();
        }

    /**
    * gethouses
    */
    public function getHouses() {
     // Perform query
        $query = "SELECT * FROM houses";
        $result = $db->query($query);
        while ($row = $result->fetch_array(MYSQLI_ASSOC))
        {
            $desciption = $row['description'];            
            echo "<p>$description</p>";    
    }
    }    
}
?> 
This is also my index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>

<?php
include ('house.class.php');
$house = new house();
echo $house->getHouses();
?>

 
Would greatly appreciate any help. Thanks in advance!
32 posts
  • Has been part of the Envato Community for over 3 years
  • Has referred 50+ members
  • Has sold $10,000+ on Envato Market
  • Has collected 1+ items on Envato Market
+2 more
robocreatif says

In $result = $db->query($query);, to what is $db referring? I’d suggest adding a private variable $db to your house class, then setting $this->db = new database(); and $this->db->dbConnect();. You can then use $this->db->mysqli->query();.

If you want to go further, I would instead extend the MySQLi class with your database class.

by
by
by
by
by
by