I am having trouble with trying to fetch and display all registered users from the database on index.php page in php mvc project designed for learning purposes. The problem is when I'm not logged in I get error
Notice: Undefined variable: users in C:\xampp\htdocs\php\App\Controllers\UserController.php
but when I am logged in I get the same error, but then undefined variable is 'name'. I tried searching for posts that have similar errors but I haven't been able to solve this. Any help is appreciated. Here is some of my code
UserController
<?php
namespace App\Controllers;
use App\Models\User;
use Core\Controller;
class UserController extends Controller
{
public function __construct($controller, $action)
{
parent::__construct($controller, $action);
$this->UserModel = $this->load_model('User');
}
public function createUserSessionAction($user)
{
$_SESSION['user_id'] = $user->id;
$_SESSION['user_email'] = $user->email;
$_SESSION['user_name'] = $user->name;
redirect('home/index');
}
public function indexAction()
{
if (!empty($_SESSION['user_name'])) {
$users = $this->UserModel->findAllUsersByName($name);
}
$this->view->render('users/index', $users);
}
User
<?php
namespace App\Models;
use Core\Database;
class User
{
private $db;
public function __construct()
{
$this->db = new Database();
}
public function findAllUsersByName($name)
{
$this->db->query('SELECT * FROM users WHERE name = :name');
$this->db->bind(':name', $name['name']);
$row = $this->db->resultSet();
if ($this->db->rowCount() > 0) {
return true;
} else {
return false;
}
}
}
index.php
<?php
use App\Models\User;
$users = new User;
?>
<table class="table table-hover">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user): ?>
<tr>
<td><?php echo $user->id; ?> </td>
<td><?php echo $user->name; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
I would like to be able to display names of all registered users from the database.