Good day, recently began to learn PHP, practicing on the development of an online store. Faced such a task. It is necessary to display the name of the current user and a photo in the header.php template.

For example, how I do it for a personal account:

Personal account controller

//получаем идентификатор юзера из сессии $userId = User::checkLogged(); //получаем информацию о пользователе из БД $user = User::getUserById($userId); require_once(ROOT . '/views/cabinet/index.php'); return true; 

Function in the User model

  $db= Db::getConnection(); $sql = 'SELECT * FROM user WHERE id = :id'; $result = $db->prepare($sql); $result->bindParam(':id', $id, PDO::PARAM_INT); //получить данные в виде массива $result->setFetchMode(PDO::FETCH_ASSOC); $result->execute(); return $result->fetch(); 

Output to personal account view

 <?php include './views/layouts/header.php' ?> <section class="main_content"> <?php echo $user['name']; ?> </section> <?php include './views/layouts/footer.php' ?> 


I do not understand how you can display the username in header.php I tried this: <?php echo User::getUserById($user['name']); ?> <?php echo User::getUserById($user['name']); ?> But it works if only go to your personal account, then the name is displayed in the header, if you go to another page disappears. Thank you in advance

  • What kind of framework do you use, apparently? - rjhdby
  • No, MVC is deployed manually, I just started to learn, it's too early for me to touch the frameworks - project6961
  • how how, in the session after logging write information. from there output to heder. PS: it would be better to learn any common MVC-framework, rather than its own city. Well, or start at least with the use of html-template engines. - teran

1 answer 1

To solve your problem, you can use SESSION , that is, in the User model, after authorization, save the received $user data into the session , for example: $_SESSION['user'] = $user; , and then you will be able to receive user data in all pages, $_SESSION['user']['name']; . This is a primitive example, just to understand the logic, it would be advisable to read the Session documentation.

After the user logs off, you need to delete this session ...

  • Thank you, what you need - project6961