How to connect two class in index file to read db_table informartion

  oop, pdo, php

I’m new to PHP PDO oop. I’m trying to create a database connection using __constructor.
It’s my database class code.

<?php
// database class
class Database
{
    // database host name
    private $db_host = "localhost";
    // database username
    private $db_user = "root";
    // database name
    private $db_name = "project_crud";
    // database password
    private $db_pass = "";

    public $conn;

    // function for create connection
    public function __construct()
    {
        try {
            $this->conn = new PDO("mysql:host=" . $this->db_host . ";dbname=" . $this->db_name, $this->db_user, $this->db_pass);
            $this->conn->exec("set names utf8");
        } catch (PDOException $e) {
            die("ERROR: Could not connect with database." . $e->getMessage());
        }
        return $this->conn;
    }
}

And it’s my other class code.

<?php

class Employees
{
    private $conn;

    private $db_table = "employees";

    public function getConnection()
    {
        $this->conn = $ob ;
    }

    public function readAllEmployee()
    {
        $data   = array();
        $query  = "SELECT * FROM $this->db_table";
        $stmt   = $this->conn->prepare($query);
        $stmt->execute();
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($result as $row) {
            $data[] = $row;
        }
        return $data;
    }
}

It’s my index code

<?php

include_once('database.php');
$db = new Database();

require_once("employee.php");
$obj = new Employees();
$obj->getConnection();

if (isset($_POST['action']) && $_POST['action'] == "view") {
    $output = '';
    $data = $obj->readAllEmployee();
    print_r($data);
}

Now I’m stuck to connect to classes to read information from the database.

Source: Ask PHP

LEAVE A COMMENT