Cloud Stack Ninja

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.



Read more here: https://stackoverflow.com/questions/64416192/how-to-connect-two-classes-to-read-information-from-the-database

Content Attribution

This content was originally published by Bappon D. Akash at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: