存储GET变量的值

时间:2013-08-26 15:52:46

标签: php mysql pdo get pagination

我在第一页上有一个搜索栏,结果显示在第二页上,并带有分页。问题是分页不适用于$_GET$_POST变量。

我的意思就像提交表单时,第二页上的网址更改为

products.php?search=something我可以看到显示的结果。

然而,当我点击分页的下一个按钮时,我得到undefined index search error,并且网址更改为products.php?page=2

那么有什么方法可以存储$_GET['search'];值,以便在页码更改时可以使用它吗?

  <form action="products.php" method="post">
  <input type="text" name="search">
  <input type="Submit">
  </form>

products.php

  <?php
        /*
         * Connect to the database (Replacing the XXXXXX's with the correct details)
         */
        try
        {
            $dbh = new PDO('mysql:host=localhost;dbname=db', 'root', '');
        }
        catch(PDOException $e)
        {
            print "Error!: " . $e->getMessage() . "<br/>";
            die();
        }
        /*
         * Get and/or set the page number we are on
         */
        if(isset($_GET['page']))
        {
            $page = $_GET['page'];
        }
        else
        {
            $page = 1;
        }


        /*
         * Set a few of the basic options for the class, replacing the URL with your own of course
         */
        $options = array(
            'results_per_page'              => 100,
            'url'                           => 'products.php?page=*VAR*',
            'db_handle'                     => $dbh
        );

        $q = $_GET['search'];
        /*
         * Create the pagination object
         */


        try

     {   

           $paginate = new pagination($page, "SELECT * FROM products where title LIKE '%$q%' order by id desc", $options);}

     catch(paginationException $e)
        {
            echo $e;
            exit();
        }


    if($paginate->success == true)
        {
            $paginate_result = $paginate->resultset->fetchAll();
            foreach($paginate_result as $row)
            {

                   echo $row['title'];
                   }

            ?>


         <?php echo "<li>"; //this is next and prev button for the pagination class if results exceed the limit. 
     echo $ball->links_html;
     echo "</li>"; ?>

3 个答案:

答案 0 :(得分:2)

将您的代码更改为此类内容......

<form action="products.php" method="get">
  <input type="text" name="search">
  <input type="Submit">
  </form>

......和......

   $options = array(
                'results_per_page'              => 100,
                'url'                           => 'products.php?search=' . urlencode($_GET['search']) . '&page=*VAR*',
                'db_handle'                     => $dbh
            );

答案 1 :(得分:-1)

最简单的解决方案可能是在表单中使用隐藏字段:

<form action="products.php" method="post">
    <input type="text" name="search">
    <input type="hidden" name="page" value="<?php echo $_GET['page']; ?>">
    <input type="Submit">
</form>

答案 2 :(得分:-1)

尝试会话变量,它们允许您存储它直到浏览器关闭(或者您切换到另一个网站?)并将其存储在页面中。

http://www.tizag.com/phpT/phpsessions.php

另一种选择是cookies,除非用户删除他们的cookie,否则它可以让你存储任意长度。

http://www.tizag.com/phpT/phpcookies.php