How to store post variables value

2019-08-28 20:30发布

问题:

I got a Index page on which search page is included, and when I submit it, it passes values to find.php through action and method post. The code is below

if($_POST['searchsubmit']=="Search"){
$cat=$_POST['searchcategory'];
$area=$_POST['searcharea'];
$term=$_POST['searchbox'];
}

The above code is written on find.php, Now when I try to implement paging through basic paging method with where conditions to make appropiate search query

$where="where approved='yes'";
        if($term!=""){
            $where.=" and name like '%$term%'";
        }
        if($cat!=""){
            $where.=" and category like '%$cat%'";
        }
        if($area!=""){
            $where.=" and area like '%$area%'";
        }
        $start=0;
        $end=5;
        if($_GET['page']!="")
        {
            $start=$_GET['page']*$end;
        }

Where $start is my initial limit, and $end is my number of records. For the first page of paging, I pass a variable page with 0 for first page

<a href="find.php?page=<?php echo 0;?>">First</a>

and my search query now becomes

$que="select * from shops ".$where." ORDER BY likes DESC  limit $start,$end";

As soon as I click on "first", My new link become "/find.php?page=0" and the post values which I recivied from index page search bar are lost.

Is there any way to retain those values ?The two methods which I though are sending them again through url with GET, or the other way is to store them in session. Is there any third method available ?

回答1:

Marc is absolutely right. Do not use the code as it is.

As an alternate solution to your problem -

  • Your page index.php (search form) submits to itself
  • Assemble your search query as querystring in index.php if its a post
  • Redirect to find.php with the assembled querystring
  • Every search information will always be in the querystring.
  • Use your pagination happily.


回答2:

The comments are correct.

Use:

// Start the session
session_start();
// Save variables into session
$_SESSION['somevalue'] = $_POST['value'];

Then when any page calls session_start it will have access to $_SESSION['somevalue']

Also, you are wide open for SQL injection. Sanitize your values to ensure no one can put arbitrary sql code into the string. if you are using mysqli it should as simple as this:

// After connecting to the DB
$_POST['somevalue' = $mysqli->real_escape_string($_POST['somevalue']);

Then be sure to hardcode quotes around string values like you are doing.

If you want to be safer you can use prepared statement instead.

Hope this helps.



标签: php post paging