PHP MySQL 表单分页

标签 php mysql pagination

我正在 PHP 中根据数据库 MySQL 中的记录进行分页。 我总共有 7 条记录要显示,我已将每页数 (resultsPerPage) 设置为 2,所以我将显示 4 页。 我正在显示两个查询的结果:

  1. 第一个是表 tblPaciente,它显示来 self 的客户的信息。
  2. 第二个是表 tblEvolucion,它显示了我应用分页所需的信息。 (显示7条记录)

我正在显示表 tblEvolucion 中的查询,并按 clmSerie 列降序显示顺序。

  • 第 1 页我想显示描述为“记录 7”和“记录 6”的记录
  • 第 2 页我想显示描述为“记录 5”和“记录 4”的记录
  • 第 3 页我想显示描述为“记录 3”和“记录 2”的记录
  • 第 4 页我想显示描述为“记录 1”的记录

我的问题是,当我按“上一页”、“下一页”或任何显示页面(1、2、3、4)时,表单正在重置,除了表单(id= frmPacienteBuscar) 为空,没有结果。我需要将其显示给我下一页,并保留第一个查询的表结果 (id=table1),并保留表单 (id=frmPacienteBuscar)。

如果我在重置表单后再次搜索,它将访问我之前访问过的页面。 例如: - 首先我加载页面。 - 然后我按页码 3 - 然后一切都是空白的,我必须用 ids 重新输入输入(id =“searchByRut”和 id =“dv”) - 然后我将立即从第 3 页访问

我试图将变量 $searchByRut 传递给我的“下一页”的 HREF,这是我在表 tblPaciente 和 tblEvolucion 中搜索所必需的,但在我按下链接后,它对我说这是 undefined index 访问任意页面。这里:

$outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=$prevpage'> Previous Page </a> ";

我试图在 PHP 代码的开头捕获它,如下所示:

$searchByRut  = $_POST["searchByRut"];

我假设我需要在每个链接的 HREF 中作为 POST 传递到 RUT 页面,但我无法捕获它,也不确定这是否是问题所在。 请让我知道任何澄清,提前致谢,

testPaginization3.php

<?php
    include_once('funcionesComunes.php');
    require_once('mysqli_connect.php');
    $outputTblEvolucion = '';
    $outputTblPaciente = $outputData = '';
    $searchByRut_error = '';
    $searchByRut = '';
    $dv_input = '';
    $iCompleteFirstQuery = $iHaveToDoSecondQuery = 0;
    $countDataFromTblPaciente = 0;
    $searchByRut  = $_POST["searchByRut"];
    if(isset($_POST['searchByRut']))
    {
        //there are just validation if my id entered to search is valid, please ignore this part:
        $error = '';
        $dv                   = $_POST["dv"];
        $dv_input             = $_POST["dv"];
        $searchByRut  = $_POST["searchByRut"];
        echo "<br>". "searchByRut={" . $searchByRut ."}";
        if ($dv == "k") 
            $dv = "K";
        $searchByRut_error = rutValidar($searchByRut, $dv, $error);
        
        //here I am checking if any error occurred in the previous validation
        if ($searchByRut_error == '')
        {
            $rut = $_POST['searchByRut'];
            $queryDatosPaciente = mysqli_query($dbc,
                                       "SELECT CONCAT(pa.clmNombres, ' ', pa.clmApellidos) as clmNombres
                                              ,pa.clmEmail
                                       FROM    tblPaciente    pa
                                         WHERE  pa.clmRut    = '$rut'
                                          "
                                ) or die('Error while searching!: {' . mysqli_error($dbc) . '}');
            $countDataFromTblPaciente = mysqli_num_rows($queryDatosPaciente);
            $iCompleteFirstQuery = 1;
            
        }
    }
    
    //this variable iCompleteFirstQuery will tell me that I have to execute second query in detail table tblEvolucion, because I found already the main record in customer table tblPaciente
    if ($iCompleteFirstQuery == 1)
    {
        if($countDataFromTblPaciente == 0)
        {
            $outputTblPaciente = 'It did not find client!';
            $iHaveToDoSecondQuery = 0;
        }
        else
        {
            //Here I just build the Table with result from query of customer tblPaciente
            $iHaveToDoSecondQuery = 1;
            $outputTblPaciente .= "<table id='table1' border='1' align='left' cellspacing='5' cellpadding='8'>";
            $outputTblPaciente .= "<tr><td align='left'><b>Name     </b></td>
                                         <td align='left'><b>Email  </b></td>
                                     </tr>";
            
            while($row = mysqli_fetch_array($queryDatosPaciente))
            {
                $nombres    = utf8_encode($row['clmNombres']);
                $email      = $row['clmEmail'];
                
                $outputTblPaciente .= "<td align='left'> $nombres      </td>
                                         <td align='left'> $email        </td>";
                $outputTblPaciente .= "</tr></table><br><br><br><br><br>";
            }
        }
    }
    
    //In this IF condition is the part that I required to make as pagination, for the result of table tblEvolucion
    if ($iHaveToDoSecondQuery == 1)
    {
        $sqlCount = "SELECT  COUNT(*)
                    FROM     tblEvolucion    ev
                    WHERE    ev.clmRut = '$rut'";
        $resultadoQueryCount = mysqli_query($dbc,$sqlCount) or die('Error to select!: {' . mysqli_error($dbc) . '}');
            
        $r = mysqli_fetch_row($resultadoQueryCount);
        $countRecordsFound = $r[0];
        echo "<br>". "countRecordsFound={" . $countRecordsFound ."}";
        echo "<br><br>";
        
        $resultsPerPage = 2;
        $totalPages = ceil($countRecordsFound / $resultsPerPage);
        
        // get the current page or set a default
        if (isset($_GET['currentPage']) && is_numeric($_GET['currentPage']))
        {
            // cast var as int
            $currentPage = (int) $_GET['currentPage'];
        }
        else
        {
            // default page num
            $currentPage = 1;
        }
        
        // if current page is greater than total pages...
        if ($currentPage > $totalPages)
        {
            // set current page to last page
            $currentPage = $totalPages;
        }
        // if current page is less than first page...
        if ($currentPage < 1)
        {
            // set current page to first page
            $currentPage = 1;
        }
        
        // the offset of the list, based on current page 
        $offset = ($currentPage - 1) * $resultsPerPage;
        
        // get the info from the db 
        $sqlDespliegaDatos ="SELECT ev.clmDescripcion
                             FROM     tblEvolucion    ev
                             WHERE    ev.clmRut    = '$rut'
                             ORDER by ev.clmSerie DESC
                             LIMIT  $offset
                                   ,$resultsPerPage";
        $resultadoQueryDespliegaDatos = mysqli_query($dbc,$sqlDespliegaDatos) or die('Error to select!: {' . mysqli_error($dbc) . '}');
        
        $iHaveToDoSecondQuery = 1;
        if($countRecordsFound == 0)
        {
            $outputData = 'No results from Table tblEvolucion!';
        }
        else
        {
            //From there I build the table with my records from tblEvolucion wish I required to be with pagination
            $outputData = '';
            $outputData .= '<table border=1 align="left" cellspacing="5" cellpadding="8">
                                        <tr><td align="left"><b>Description                  </b></td>
                                    </tr>';
                                    
            while ($list = mysqli_fetch_assoc($resultadoQueryDespliegaDatos))
            {
                $descripcion               = utf8_encode($list['clmDescripcion']);
                
                $outputData .= '<tr>';
                $outputData .= "<td align='left'><textarea id='descripcion' name='descripcion' tabindex='4' cols='50' rows='6' maxlength='1000'
                                                           value = '".$descripcion."' 
                                                           readonly>".($descripcion)."</textarea>
                                </td>";
                $outputData .= '</tr>';
                
            }
            $outputData .= '</table>';
            
            $outputTblEvolucion = '';
            /******  build the pagination links ******/
            // range of num links to show
            $range = 3;
            
            // if not on page 1, don't show back links
            if ($currentPage > 1)
            {
                // show << link to go back to page 1
                $outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=1'> << </a> ";
                // get previous page num
                $prevpage = $currentPage - 1;
                // show < link to go back to 1 page
                $outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=$prevpage'> Previous Page </a> ";
            }
            
            // loop to show links to range of pages around current page
            for ($x = ($currentPage - $range); $x < (($currentPage + $range) + 1); $x++)
            {
                // if it's a valid page number...
                if (($x > 0) && ($x <= $totalPages))
                {
                    // if we're on current page...
                    if ($x == $currentPage)
                    {
                        // 'highlight' it but don't make a link
                        $outputTblEvolucion .= " [<b>$x</b>] ";
                    // if not current page...
                    } else
                    {
                        // make it a link
                        $outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=$x'>$x</a> ";
                    }
                }
            }
                            
            // if not on last page, show forward and last page links        
            if ($currentPage != $totalPages)
            {
                // get next page
                $nextpage = $currentPage + 1;
                // echo forward link for next page
                //Here is which I think I am doing something wrong and I though to pass also my variable searchByRut but I am not able to received after pressing click on "Next Page"
                $outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=$nextpage"
                                                                          ."&searchByRut=$searchByRut
                                                                            '>Next Page</a> ";
                // echo forward link for lastpage
                $outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=$totalPages'>>></a> ";
            } // end if
        }
    }
?>
<html>
    <head>
        <title>Pagination with Form</title>
    </head>
    <body>
        <h1>Pagination with Form</h1>
        <form id="frmPacienteBuscar" action="" method="post">
            <fieldset>
                <span class="error"><?= $searchByRut_error ?></span><br>
                RUT: <input name="searchByRut" id="searchByRut" type="text" placeholder="Search by RUT.." tabindex="2" size="15" maxlength="8"
                            value="<?= $searchByRut ?>" > - 
                     <input name="dv" id="dv" type="text" value="<?= $dv_input ?>" size="1" tabindex="2" maxlength="1"
                            value="<?= $dv_input ?>" >  Sample: 12345678-1<br>
                <button name="buscar" type="submit" id="contact-submit" data-submit="...Sending">Search</button><br>
            </fieldset>
        </form>
        <?php
            /*Here I will be printing the result of:
                - the main table from tblPaciente
                - the table which I required to do pagination tblEvolucion
                - the links to navigate to the next and previous pages
            */
            echo $outputTblPaciente;
            echo "<br>";
            echo $outputData;
            echo "<br>";
            echo $outputTblEvolucion;
        ?>
    </body>
</html>

 

 

Pagination Screenshot After Pressing any page, the form is empty again

最佳答案

感谢@ArtisticPhoenix的评论,我将发布修改后的代码的解决方案:

确切地说,我将方法从 POST 修改为 GET,并且我在代码开头也采用了这种方式:

$searchByRut = isset($_POST["searchByRut"]) ? $_POST["searchByRut"] : '';

新代码:

<?php
    include_once('funcionesComunes.php');
    require_once('mysqli_connect.php');
    $outputTblEvolucion = '';
    $outputTblPaciente = $outputData = '';
    $searchByRut_error = '';
    $searchByRut = '';
    $dv_input = '';
    $iCompleteFirstQuery = $iHaveToDoSecondQuery = 0;
    $countDataFromTblPaciente = 0;
    //$searchByRut = $_GET["searchByRut"];
    $searchByRut = isset($_GET["searchByRut"]) ? $_GET["searchByRut"] : '';
    $dv = isset($_GET["dv"]) ? $_GET["dv"] : '';
    echo "<br>". "0searchByRut={" . $searchByRut ."}";
    echo "<br>". "0dv={" . $dv ."}";
    if(isset($_GET['searchByRut']))
    {
        //there are just validation if my id entered to search is valid, please ignore this part:
        $error = '';
        $dv                   = $_GET["dv"];
        $dv_input             = $_GET["dv"];
        $searchByRut  = $_GET["searchByRut"];
        echo "<br>". "searchByRut={" . $searchByRut ."}";
        if ($dv == "k") 
            $dv = "K";
        $searchByRut_error = rutValidar($searchByRut, $dv, $error);

        //here I am checking if any error ocurred in the previous validation
        if ($searchByRut_error == '')
        {
            $rut = $_GET['searchByRut'];
            $queryDatosPaciente = mysqli_query($dbc,
                                       "SELECT CONCAT(pa.clmNombres, ' ', pa.clmApellidos) as clmNombres
                                              ,pa.clmEmail
                                       FROM    tblPaciente    pa
                                         WHERE  pa.clmRut    = '$rut'
                                          "
                                ) or die('Error while searching!: {' . mysqli_error($dbc) . '}');
            $countDataFromTblPaciente = mysqli_num_rows($queryDatosPaciente);
            $iCompleteFirstQuery = 1;

        }
    }

    //this variable iCompleteFirstQuery will tell me that I have to execute second query in detail table tblEvolucion, because I found already the main record in customer table tblPaciente
    if ($iCompleteFirstQuery == 1)
    {
        if($countDataFromTblPaciente == 0)
        {
            $outputTblPaciente = 'It did not find client!';
            $iHaveToDoSecondQuery = 0;
        }
        else
        {
            //Here I just build the Table with result from query of customer tblPaciente
            $iHaveToDoSecondQuery = 1;
            $outputTblPaciente .= "<table id='table1' border='1' align='left' cellspacing='5' cellpadding='8'>";
            $outputTblPaciente .= "<tr><td align='left'><b>Name     </b></td>
                                         <td align='left'><b>Email  </b></td>
                                     </tr>";

            while($row = mysqli_fetch_array($queryDatosPaciente))
            {
                $nombres    = utf8_encode($row['clmNombres']);
                $email      = $row['clmEmail'];

                $outputTblPaciente .= "<td align='left'> $nombres      </td>
                                         <td align='left'> $email        </td>";
                $outputTblPaciente .= "</tr></table><br><br><br><br><br>";
            }
        }
    }

    //In this IF condition is the part that I required to make as pagination, for the result of table tblEvolucion
    if ($iHaveToDoSecondQuery == 1)
    {
        $sqlCount = "SELECT  COUNT(*)
                    FROM     tblEvolucion    ev
                    WHERE    ev.clmRut = '$rut'";
        $resultadoQueryCount = mysqli_query($dbc,$sqlCount) or die('Error to select!: {' . mysqli_error($dbc) . '}');

        $r = mysqli_fetch_row($resultadoQueryCount);
        $countRecordsFound = $r[0];
        echo "<br>". "countRecordsFound={" . $countRecordsFound ."}";
        echo "<br><br>";

        $resultsPerPage = 2;
        $totalPages = ceil($countRecordsFound / $resultsPerPage);

        // get the current page or set a default
        if (isset($_GET['currentPage']) && is_numeric($_GET['currentPage']))
        {
            // cast var as int
            $currentPage = (int) $_GET['currentPage'];
        }
        else
        {
            // default page num
            $currentPage = 1;
        }

        // if current page is greater than total pages...
        if ($currentPage > $totalPages)
        {
            // set current page to last page
            $currentPage = $totalPages;
        }
        // if current page is less than first page...
        if ($currentPage < 1)
        {
            // set current page to first page
            $currentPage = 1;
        }

        // the offset of the list, based on current page 
        $offset = ($currentPage - 1) * $resultsPerPage;

        // get the info from the db 
        $sqlDespliegaDatos ="SELECT ev.clmDescripcion
                             FROM     tblEvolucion    ev
                             WHERE    ev.clmRut    = '$rut'
                             ORDER by ev.clmSerie DESC
                             LIMIT  $offset
                                   ,$resultsPerPage";
        $resultadoQueryDespliegaDatos = mysqli_query($dbc,$sqlDespliegaDatos) or die('Error to select!: {' . mysqli_error($dbc) . '}');

        $iHaveToDoSecondQuery = 1;
        if($countRecordsFound == 0)
        {
            $outputData = 'No reults from Table tblEvolucion!';
        }
        else
        {
            //From there I build the table with my records from tblEvolucion wish I required to be with pagination
            $outputData = '';
            $outputData .= '<table border=1 align="left" cellspacing="5" cellpadding="8">
                                        <tr><td align="left"><b>Description                  </b></td>
                                    </tr>';

            while ($list = mysqli_fetch_assoc($resultadoQueryDespliegaDatos))
            {
                $descripcion               = utf8_encode($list['clmDescripcion']);

                $outputData .= '<tr>';
                $outputData .= "<td align='left'><textarea id='descripcion' name='descripcion' tabindex='4' cols='50' rows='6' maxlength='1000'
                                                           value = '".$descripcion."' 
                                                           readonly>".($descripcion)."</textarea>
                                </td>";
                $outputData .= '</tr>';

            }
            $outputData .= '</table>';

            $outputTblEvolucion = '';
            /******  build the pagination links ******/
            // range of num links to show
            $range = 3;

            // if not on page 1, don't show back links
            if ($currentPage > 1)
            {
                // show << link to go back to page 1
                //$outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=1'> << </a> ";
                $outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=1"
                                                                          ."&searchByRut=$searchByRut"
                                                                          ."&dv=$dv
                                                                            '>First Page</a> ";
                // get previous page num
                $prevpage = $currentPage - 1;
                // show < link to go back to 1 page
                //$outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=$prevpage'> Previous Page+ </a> ";
                $outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=$prevpage"
                                                                          ."&searchByRut=$searchByRut"
                                                                          ."&dv=$dv
                                                                            '>Previous Page+ </a> ";

            }

            // loop to show links to range of pages around current page
            for ($x = ($currentPage - $range); $x < (($currentPage + $range) + 1); $x++)
            {
                // if it's a valid page number...
                if (($x > 0) && ($x <= $totalPages))
                {
                    // if we're on current page...
                    if ($x == $currentPage)
                    {
                        // 'highlight' it but don't make a link
                        $outputTblEvolucion .= " [<b>$x</b>] ";

                    // if not current page...
                    } else
                    {
                        // make it a link
                        //$outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=$x'>$x</a> ";
                        //ERROR
                        $outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=$x"
                                                                                ."&searchByRut=$searchByRut"
                                                                                ."&dv=$dv
                                                                                    '>$x</a> ";

                    }
                }
            }

            // if not on last page, show forward and last page links        
            if ($currentPage != $totalPages)
            {
                // get next page
                $nextpage = $currentPage + 1;
                // echo forward link for next page
                //Here is wich I think I am doing something wrong and I though to pass also my variable searchByRut but I am not able to received after pressing click on "Next Page"
                $outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=$nextpage"
                                                                          ."&searchByRut=$searchByRut"
                                                                          ."&dv=$dv
                                                                            '>Next Page</a> ";
                // echo forward link for lastpage
                $outputTblEvolucion .= " <a href='{$_SERVER['PHP_SELF']}?currentPage=$totalPages"
                                                                          ."&searchByRut=$searchByRut"
                                                                          ."&dv=$dv
                                                                            '>Last Page</a> ";
            } // end if
        }
    }
?>
<html>
    <head>
        <title>Pagination with Form</title>
    </head>
    <body>
        <h1>Pagination with Form</h1>
        <form id="frmPacienteBuscar" action="" method="get">
            <fieldset>
                <span class="error"><?= $searchByRut_error ?></span><br>
                RUT: <input name="searchByRut" id="searchByRut" type="text" placeholder="Search by RUT.." tabindex="2" size="15" maxlength="8"
                            value="<?= $searchByRut ?>" > - 
                     <input name="dv" id="dv" type="text" value="<?= $dv_input ?>" size="1" tabindex="2" maxlength="1"
                            value="<?= $dv_input ?>" >  Sample: 12345678-1<br>
                <button name="buscar" type="submit" id="contact-submit" data-submit="...Sending">Search</button><br>
            </fieldset>
        </form>
        <?php
            /*Here I will be printing the result of:
                - the main table from tblPaciente
                - the table which I required to do pagination tblEvolucion
                - the links to navigate to the next and previous pages
            */
            echo $outputTblPaciente;
            echo "<br>";
            echo $outputData;
            echo "<br>";
            echo $outputTblEvolucion;
        ?>
    </body>
</html>

关于PHP MySQL 表单分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49798723/

相关文章:

PHP、MYSQL,根据 3 个下拉列表中的所有值为 true 选择结果

php - laravel 发送邮件的最大收件人数是多少?

php - Mysqli 查询 UPDATE WHERE

mysql - 我可以只在 JOIN 失败的地方使用 MySQL SELECT 行吗?

mysql - 合并 2 个 SQL 查询/表

php - PHP高效的分页查询方式

angularjs - 使用 AngularJS UI Bootstrap 分页时返回正确的页面

php - 在 Ubuntu ( Linux ) 上使用 Lamp 安装 Mongodb

mysql - JPA多对多关系不插入生成的表

asp.net - 提高gridview的分页性能?