-2

I've two files in one directory named (classes )which contain classes, first one for main class (Database ) which build to connect to the database. And the second one (Branch ) extends Database class which made to get data from the database.

When I try to run "getBranch" function I got an error says :

Uncaught Error: Class 'Database' not found in C:\xampp\htdocs\branches\classes\branch.php

Please find the codes below and advise what's required.

database.php:

<?php

  class Database {
    private $host;
    private $user;
    private $pwd;
    private $dbName;
    public $conn;

    public function connect() {
      $this->host = "localhost";
      $this->user = "root";
      $this->pwd = "";
      $this->dbName = "branchs";
      //create connection
      $conn = new mysqli($this->host, $this->user, $this->pwd, $this->dbName);
      //chech connection
      if ($conn->connect_error) {
        die("Connection failed :" . $conn->connect_error);
      } else {
        echo "Success";
      }

      return $conn;

    }

  }

?>

branch.php :

<?php

    class Branch extends Database {

      public function getBranch() {

      $sql = "SELECT * FROM branches";
      $result = $this->connect()->query($sql);

      if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
          echo "Name :" . $row['brName'] . "City :" . $row['brCity'] . "<br>";
        }
      } else {
        echo "0 results";
      }

      }

    }

?>
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
mmiz
  • 1
  • 1

3 Answers3

3

You must include "database.php" file into top of "branch.php" file

<?php include 'database.php'; ?>

Also, take a look about autoload concept with php. https://www.php.net/manual/en/language.oop5.autoload.php

Lounis
  • 597
  • 7
  • 15
1

You need to call database.php file in the branch.php (because Branch Class does not know that Database Class exists) by using require() or include() - depends. 2nd option is to use namespaces and 'use' statements for easier further development. https://www.php.net/manual/en/language.namespaces.php

0

You should do require_once('database.php');to inherit the class entities from the parent class.

Seungju
  • 101
  • 6