PHP pagination loses variable on other pages

后端 未结 2 511
天命终不由人
天命终不由人 2021-01-26 16:17

I have a value that is passed to my search results page via $_POST and stored in a variable called $term. The variable is then in a MySQL query which then runs to display the s

相关标签:
2条回答
  • 2021-01-26 16:58

    the other solution is to use GET request for search and get the term by $_GET['term'] and append to the generated links '&term='. $_GET['term']. This would be done easy. The main disadvantage of usin $_SESSION['term'] is that if you leave the page to homepage for example, this variable will stay set until the session expire and could case some future troubles.

    0 讨论(0)
  • 2021-01-26 17:11

    Variables in PHP do not persist across pages. Except for some of them of course, but regular $page or $whatever will not persist. You will load a page, have some vars in it, then after the page is fully loaded in the browser, those variables will be gone.

    The recommendation is to use session_start() at the top of your scripts, in all pages, and use $_SESSION['variable']=... to store variables. This way, they will persist across pages.

    The easiest fix:

    $page = $_GET['page']; 
    

    Replace that line with this:

    $page = isset($_SESSION['page']) && is_numeric($_SESSION['page']) ? $_SESSION['page'] : 0;
    $_SESSION['page'] = $page;
    

    And add session_start() at the top of every script. If you have a common head include, or config.php with mysql authentication data, put it at the top of that file.

    0 讨论(0)
提交回复
热议问题