Im working on a e-commerce for a school project, using MVC for the first time, everything seems to works fine exept for displaying products from the db and displaying users also from the db, since the problem may be the same i will just upload the code for the users because its way short.
First of all i will upload index.php, where i create the session and the connection, and also send the uri to the router (sorry for italians comment everything else is written in english)
<?php
require_once __DIR__ . '/routers/switchrouter.php';
require_once __DIR__ . '/config/dbconfig.php';
// inizia la sessione se non esiste già
if(!isset($_SESSION)){
session_start();
}
// Crea un'istanza di mysqli utilizzando le variabili dal file dbconfig.php
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connessione al database fallita: " . $conn->connect_error);
}
//echo "Connected successfully";
$uri = trim($_SERVER['REQUEST_URI'], '/');
$router = new SwitchRouter($conn); // Passa direttamente un'istanza di mysqli al costruttore di SwitchRouter
$router->route($uri);
?>
i dont think router is important for my problem, so i will not upload the code unless someone say it is important.
Now we have userrepository.php, where i do all the query (they works cuz i tried them directly in the db):
<?php
namespace Repositories;
require_once __DIR__ . '/repository.php';
require_once __DIR__ . '/../models/user.php';
use mysqli;
class UserRepository extends Repository
{
function __construct(mysqli $conn)
{
parent::__construct($conn);
}
// Ottiene un utente tramite email
public function getOne($attemptedEmail)
{
$sqlquery = "SELECT * FROM USERS WHERE email=?";
$stmt = $this->connection->prepare($sqlquery);
if ($stmt === false) {
die("Prepare failed: " . $this->connection->error);
}
$stmt->bind_param("s", $attemptedEmail);
$stmt->execute();
$result = $stmt->get_result();
$userData = $result->fetch_assoc();
if ($userData) {
return new ModelsUser($userData);
} else {
return null;
}
}
// Ottiene un utente tramite ID
public function getOneById($id)
{
$sqlquery = "SELECT * FROM USERS WHERE user_id=?";
$stmt = $this->connection->prepare($sqlquery);
if ($stmt === false) {
die("Prepare failed: " . $this->connection->error);
}
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$userData = $result->fetch_assoc();
if ($userData) {
return new ModelsUser($userData);
} else {
return null;
}
}
// Verifica se un utente esiste tramite ID
public function existsById($id)
{
$sqlquery = "SELECT * FROM USERS WHERE user_id=?";
$stmt = $this->connection->prepare($sqlquery);
if ($stmt === false) {
die("Prepare failed: " . $this->connection->error);
}
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$userData = $result->fetch_assoc();
if ($userData) {
return new ModelsUser($userData);
} else {
return null;
}
}
// Ottiene tutti gli utenti
public function getAll()
{
$sqlquery = "SELECT * FROM USERS";
$result = $this->connection->query($sqlquery);
if ($result === false) {
die("Query failed: " . $this->connection->error);
}
return $result->fetch_all(MYSQLI_ASSOC);
}
// Ottiene tutte le email degli utenti
private function getAllEmail()
{
$sqlquery = "SELECT DISTINCT email FROM USERS";
$result = $this->connection->query($sqlquery);
if ($result === false) {
die("Query failed: " . $this->connection->error);
}
return $result->fetch_all(MYSQLI_ASSOC);
}
// Registra un nuovo utente
public function registerUser($newUser)
{
$sqlquery = "INSERT INTO USERS (full_name, email, password, role, image) VALUES (?, ?, ?, ?, ?)";
$stmt = $this->connection->prepare($sqlquery);
if ($stmt === false) {
die("Prepare failed: " . $this->connection->error);
}
$stmt->bind_param("sssis", $fullName, $email, $password, $role, $image);
$fullName = $newUser->getFullName();
$email = $newUser->getEmail();
$password = $newUser->getPassword();
$role = $newUser->getRole();
$image = $newUser->getImage();
if ($this->validateEmail($newUser->getEmail())) {
$stmt->execute();
} else {
echo "Email already exists";
}
}
// Aggiorna un utente esistente
public function updateUser($editedUser, $pwChange)
{
$id = $editedUser->getId();
$fullName = $editedUser->getFullName();
$email = $editedUser->getEmail();
$address = $editedUser->getAddress();
if ($pwChange) {
$password = $editedUser->getPassword();
$sqlquery = "UPDATE USERS SET full_name=?, email=?, password=?, address=? WHERE user_id=?";
} else {
$sqlquery = "UPDATE USERS SET full_name=?, email=?, address=? WHERE user_id=?";
}
$stmt = $this->connection->prepare($sqlquery);
if ($stmt === false) {
die("Prepare failed: " . $this->connection->error);
}
if ($pwChange) {
$stmt->bind_param("ssssi", $fullName, $email, $password, $address, $id);
} else {
$stmt->bind_param("sssi", $fullName, $email, $address, $id);
}
$stmt->execute();
}
// Elimina un utente
public function deleteUser($id)
{
$sqlquery = "DELETE FROM USERS WHERE user_id=?";
$stmt = $this->connection->prepare($sqlquery);
if ($stmt === false) {
die("Prepare failed: " . $this->connection->error);
}
$stmt->bind_param("i", $id);
$stmt->execute();
}
// Verifica se l'email dell'utente è unica
public function validateEmail($email)
{
$emailList = $this->getAllEmail();
foreach ($emailList as $em) {
if ($em['email'] == $email) return false;
}
return true;
}
// Ottiene le credenziali di accesso dell'utente tramite email
public function getCredentials($email)
{
$sqlquery = "SELECT password FROM USERS WHERE email=?";
$stmt = $this->connection->prepare($sqlquery);
if ($stmt === false) {
die("Prepare failed: " . $this->connection->error);
}
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
return $row['password'];
}
// Ottiene il ruolo dell'utente tramite email
public function getRole($email)
{
$sqlquery = "SELECT role FROM USERS WHERE email=?";
$stmt = $this->connection->prepare($sqlquery);
if ($stmt === false) {
die("Prepare failed: " . $this->connection->error);
}
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
return $result->fetch_assoc()['role'];
}
}
then we have userservice.php:
<?php
namespace Services;
require_once __DIR__ . '/../repositories/userrepository.php';
require_once __DIR__ . '/../models/user.php';
use RepositoriesUserRepository;
use mysqli;
class UserService {
private $userRepository;
function __construct(mysqli $conn) {
$this->userRepository = new UserRepository($conn);
}
// Rimuovi questo metodo se non è necessario
// public function getConnection() {
// return $this->userRepository->getConnection();
// }
// Restituisce un user in base all'email
public function getOne($userName) {
return $this->userRepository->getOne($userName);
}
// Restituisce un user in base all'ID
public function getOneById($id) {
return $this->userRepository->getOneById($id);
}
// Verifica se un user esiste in base all'ID
public function existsById($id) {
return $this->userRepository->existsById($id);
}
// Registra un nuovo user
public function registerUser($newUser) {
$this->userRepository->registerUser($newUser);
}
// Restituisce tutti gli user
public function getAll() {
return $this->userRepository->getAll();
}
// Aggiorna un user
public function updateUser($editedUser, $pwChange) {
$this->userRepository->updateUser($editedUser, $pwChange);
}
// Verifica se l'email è valida
public function validateEmail($email) {
return $this->userRepository->validateEmail($email);
}
// Restituisce le credenziali di un user in base all'email
public function getCredentials($email) {
return $this->userRepository->getCredentials($email);
}
// Elimina un user
public function deleteUser($id) {
$this->userRepository->deleteUser($id);
}
// Restituisce il ruolo di un user in base all'email
public function getRole($email) {
return $this->userRepository->getRole($email);
}
}
?>
from the controller i will just upload the part where the problem may be, everything else like login, signup etc works fine
function usersView()
{
session_start();
if (isset($_SESSION['role'])) {
if ($_SESSION['role'] == Role::Admin) {
$users = $this->userService->getAll();
require '../../app/views/admin/users.php';
}
} else {
$this->loginView();
}
}
for last we have the view, where the users should be displayed
<?php
require __DIR__ . '/../header.php';
?>
</header>
<!-- fine header section -->
<!-- inizio main section -->
<main class="container">
<section id="orders" class="mt-5">
<h2>Users</h2>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Immagine</th>
<th scope="col">Nome</th>
<th scope="col">Email</th>
<th scope="col">Ruolo</th>
<th scope="col">Azioni</th>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user) : ?>
<tr>
<td><?= $user->getId() ?></td>
<td><img src="<?= $user->getImage() ?>" alt="user image" width="50" height="50"></td>
<td><?= $user->getFullName() ?></td>
<td><?= $user->getEmail() ?></td>
<td><?= $user->getRoleName() ?></td>
<td>
<a href="/users/editView?editUser=<?= $user->getId() ?>" class="btn btn-primary">Edit</a>
<a href="/users/delete?deleteUser=<?= $user->getId() ?>" class="btn btn-danger">Delete</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</section>
</main>
<!-- fine main section -->
<?php
require __DIR__ . '/../footer.php';
?>
i tried some debugging, not very good at it and didnt had any results.
MbareSimo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.