0

I'm new. Below is the beginning of an attempt to interface with a database. Please let me know if the syntax is not correct, it seems to work on my localhost.

I think I could have typed class Database extends Mysqli, right? which would then have made the methods of Mysqli directly accessible to Database rather than through an instance created in the class itself. Would that have been preferable to what I have done?

class Database {

    #The variable that stores the database handle
    public $db;

    #The Database objects's datbase parameters
    public $host;
    public $user;
    public $password;
    public $database;

    #creates a Database object with the required databases details
    public function __construct($host, $user, $password, $database) {
        $this->host = $host;
        $this->user = $user;
        $this->password = $password;
        $this->database = $database;
    }

    #Stores the database handle as a var $db of the Database instance 
    public function connect() {
        if ($this->db = new Mysqli($this->host, $this->user, $this->password, $this->database)) {
            if ($this->db->connect_errno) {
                echo "No connection could be made <br/>";
            } else {
                echo "database succesfully connected <br/>";
            }
        }
    }
}
Zach Smith
  • 8,458
  • 13
  • 59
  • 133

1 Answers1

1

If your class Database represents the database handle, then it should not have it public:

#The variable that stores the database handle
public $db;

Otherwise you would not encapsulate that detail and therefore you wouldn't need your class at all.

Next to that, when you start to write classes, echo does not belong in there:

    if ($this->db = new Mysqli($this->host, $this->user, $this->password, $this->database)) {
        if ($this->db->connect_errno) {
            echo "No connection could be made <br/>";
        } else {
            echo "database succesfully connected <br/>";
        }
    }

Because classes consists of methods returning via their return value and not via standard output. Instead you want to throw an exception here. Which is also a feature of Mysqli already, therefore, you don't need to write that error handling code your own to get started:

After getting these more or less obvious ones out of the way, you're asking yourself whether or not you should inherit mysqli instead of aggregating it.

I actually can not tell you. So far the code you've shared just shows standard functionality of a mysqli therefore I would suggest to drop that class completely as the code looks superfluous. So I would say: neither. I see no reason for your Database class as you just could use mysqli instead.

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836