简体   繁体   中英

How to store data to use across all pages?

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM