PHP pagination loses variable on other pages

后端 未结 2 515
天命终不由人
天命终不由人 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 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.

提交回复
热议问题