Create php MVC application. Cabinet main page

Home » Tutorials » PHP+MySQL » Create php MVC application. Cabinet main page
Today our task is cabinet main page making. This page requires large html coding. That’s why I will use ready-to-use html template because I want to draw your attention to the more important tasks for you. You can download template by this link.
After page template creating we need to create CabinetController and CabinetModel. In controller as always we define private property – template for rendering and create default method (index), which will render the page with some dynamic data. This data is stored in $pageData array. First of all we will print some basic common statistics – count of orders, products and users. For this purpose we write appropriate methods – getOrdersCount(), getOrdersProductsCount() and getUsersCount(). PHP code of these methods is identical except for table names from which we get the data. Methods return count of rows not specific data. That’s why in sql query we must use COUNT(*) SQL function. And we will get result with fetchColumn() method.

Code lesson (CabinetController.php)

<?php

class CabinetController extends Controller {

    private $pageTpl = "/views/cabinet.tpl.php";

    public function __construct() {
        $this->model = new CabinetModel();
        $this->view = new View();
    }

    public function index() {
        $this->pageData['title'] = "Кабинет";

        $ordersCount = $this->model->getOrdersCount();
        $this->pageData['ordersCount'] = $ordersCount;

        $productsCount = $this->model->getProductsCount();
        $this->pageData['productsCount'] = $productsCount;

        $usersCount = $this->model->getUsersCount();
        $this->pageData['usersCount'] = $usersCount;

        $this->view->render($this->pageTpl, $this->pageData);
    }

}

 ?>

Code lesson (CabinetModel.php)

<?php

class CabinetModel extends Model {

    public function getOrdersCount() {
        $sql = "SELECT COUNT(*) FROM orders";
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $res = $stmt->fetchColumn();
        return $res;
    }

    public function getProductsCount() {
        $sql = "SELECT COUNT(*) FROM products";
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $res = $stmt->fetchColumn();
        return $res;
    }

    public function getUsersCount() {
        $sql = "SELECT COUNT(*) FROM users";
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $res = $stmt->fetchColumn();
        return $res;
    }


}

 ?>

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

Pin It on Pinterest

Share This