Databases

How to easily interact with Databases

To interact with databases, we first have to create a config.php file where we define constants about the connection information to the database.

The contents of the config.php should be

<?php
// config.php
const DB_TYPE = 'mysql';
const DB_HOST = 'localhost';
const DB_NAME = 'college';
const DB_USER = 'root';
const DB_PASS = '';
?>

These constants are used in the Database class to create the DSN(Data Source Name) string for PDO object to connect to the database.

Create Database Class

After creating the config file, create a database.php file where we would create a class which would interact with database.

This class should extend the Database class provided at sirJuni\Framework\Model\Database.

<?php   // model.php
// import config file
require_once "config.php";
require_once __DIR__ . "\\..\\vendor\\autoload.php";

use sirJuni\Framework\Model\Database;

class DB extends Database {
    public function __construct() {
        $this->dbConnect();
    }
    
    public function getUsers() {
        $query = "SELECT * FROM users";
        $stmt = $this->db->query($query);
        return $stmt->fetch();
    }
}

?>

After creating this class, we have to create a constructor for this class, and in this constructor we have to call the predefined $this->dbConnect() method which creates the connection and provides us with $this->db resource variable. This $db property of DB class, is an instance of PDO() class.

After all this is done, we can create custom methods on this class to interact with the database the way we want.

Using DB with Controllers

We can now use this DB class above, with controllers by requiring this model.php file in the controllers.php file and creating an instance of the DB class.

<?php
// controllers.php
require_once "model.php";

// controller code
    $db = new DB();
    $all_users = $db->getUsers();
// controller code

Last updated