dtc66318 2018-05-18 07:30
浏览 34
已采纳

如何存储要在所有页面中使用的数据?

I am having some issues trying to make a project with a login because I need to store the users' data into variables so I can use it across all pages.

Actually, the login calls a function in the model where it checks if the user exists, and if so, it returns the data obtained in the query to the controller and the controller then calls a require_once("example.php") which makes me able to use the data to print it in the screen, but if I switch the page, the data get's lost because it hasn't been called, like this (it has been simplified):

Controller

function example() {
    $exampleUser = $_POST['username'];
    $examplePass = $_POST['password'];
    $example = new example_model();
    $exampleResults= $example->do_example($exampleUser, $examplePass);
    require_once("example1.php");
}

Model

function do_example($exampleUser, $examplePass) {
    $exampleResults = mysqli_fetch_assoc($connection->query("SELECT * FROM users WHERE username = '$exampleUser' AND password = '$examplePass'");
return $exampleResults;
}

View example1.php

<?php
    echo $example['username'];
    // RESULTS IN DISPLAYING "ExampleName"
?>

View example2.php

<?php
        echo $example['username'];
        // ERROR BECAUSE IT DOESN'T HAVE THE DATA STORED ANYMORE
        // AND I DON'T WANT TO CALL A FUNCTION TO GET THE DATA FOR THE USER AGAIN AFTER EACH PAGE CHANGE
?>

I have been thinking to use $_SESSION variables to store the data I need from te logged in user so I can use it across all pages (its name and Id, mostly) and it worked so far, but but I am wondering if doing it that way is a good practice, or if there is a better one? Or how should I store the data obtained from the login so I can use it within all the pages without problem?

  • 写回答

1条回答 默认 最新

  • dongmei9203 2018-05-18 07:35
    关注

    For that purpose you need to use php sessions

    // initate session on all pages

    session_start():
    

    After you will have $_SESSION VARIABLES Array accessible on all pages where seasion is initiated.

    To define a variable, you follow the same syntax as an associative array:

    $_SESSION['name'] = value ; 
    

    When done destroy the session by

    session_destroy();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应