Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shahr's avatar
Level 10

How to show data users from the database on the site with MVC-PHP 8?

How to show data users from the database on the site with MVC-PHP 8?

I have an mvc folder, In the folder are 5 file

  • index.php
  • route.php
  • User.php
  • UserController.php
  • view.php

index.php

<?php

require_once 'route.php';

route.php

<?php

require_once 'UserController.php';

$controller = new UserController();

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if ($_SERVER['REQUEST_URI'] === '/') {
        $controller->index();
    }
}

UserController.php

<?php

require_once 'User.php';

class UserController {
    private $user;

    public function __construct() {
        $this->user = new User();
    }

    public function index() {
        $users = $this->user->getAll();
        require 'view.php';
    }

    // Add more methods here to handle other requests
}

User.php

<?php

class User {
    private $db;

    public function __construct() {
        $this->db = new PDO('mysql:host=localhost;dbname=php', 'root', '');
    }

    public function getAll() {
        $stmt = $this->db->query('SELECT * FROM users');
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    // Add more methods here to interact with the database
}

view.php

<!DOCTYPE html>
<html>
<head>
    <title>Users</title>
</head>
<body>
    <h1>Users</h1>
    <ul>
        <?php foreach ($users as $user): ?>
            <li><?= $user['id'] ?></li>
            <li><?= $user['name'] ?></li>
            <li><?= $user['email'] ?></li>
        <?php endforeach ?>
    </ul>
</body>
</html>

This code does not display any data correctly.

0 likes
2 replies

Please or to participate in this conversation.