0

I am an amateur, and therefore I have difficulty in solving the problem. I have an abstract class, I will inherit 3 classes from it, for outputting and writing data to the database. Here is a code snippet:
class Database

public function __construct(){  
    $conn = new mysqli($this->host, $this->user, $this->pass, $this->dbname);
}

Abstract class

abstract class Main_Product_Class
{
    public function __construct(){
        $this->db = new Database();
    }
    
    abstract public function getProducts($fields,$tablename);    
}

class Product


class Product extends Main_Product_Class
{
    public function __construct(){
        parent::__construct();    
    }
    
    public function getProducts($fields, $tablename){
        $array = array();
    
        $query = "SELECT $fields FROM $tablename ";
        $result = mysqli_query($this->db, $query);
    
        while($row = mysqli_fetch_assoc($result)){
            $array[] = $row;
        }
        return $array;
    }
}

index.php

$data = new Product();
$array = $data->getProducts('*', 'product');

I get an error

Warning: mysqli_query() expects parameter 1 to be mysqli, object given in Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null given in

Could you tell me how to solve the error and a few words about whether I am creating the structure correctly. I want to demonstrate code structuring in meaningful classes that extend each other, to see an abstract class for the main product logic.

M. Eriksson
  • 13,450
  • 4
  • 29
  • 40
David
  • 53
  • 2
  • 5
  • your question title should be about `creating a DB connexion in one class and using it in other classes`. Show more code from `Database`, learn to read the error messages, they tend to be very specific. – YvesLeBorg Dec 27 '20 at 11:20
  • 1
    The function `mysqli_query()` requires the actual mysqli-instance as first argument. `$this->db` is your own custom database class, not the mysqli-instance. – M. Eriksson Dec 27 '20 at 11:33
  • `$conn = new mysqli...` is discarded immediately, since `$conn` is just a local function variable and not an object property. – deceze Dec 27 '20 at 11:45

0 Answers0