【问题标题】:PHP MySQL Form PaginationPHP MySQL 表单分页
【发布时间】:2018-09-22 17:38:15
【问题描述】:

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

1.-First is table tblPaciente which shows information from my client.
2.-Second is table tblEvolucion wich shows information which I required to apply the pagination. (7 records to display)

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

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

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

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

我试图在我的“下一页”的 HREF 中传递变量 $searchByRut,这是我在表 tblPaciente 和 tblEvolucion 中搜索所必需的,但它告诉我这是在我按下链接后未定义的索引访问任何页面。这里:

$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 ocurred 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 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> ";
                // 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 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
                                                                            '>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>

【问题讨论】:

  • 如果你使用分页和搜索,你应该使用$_GET而不是post。这个$searchByRut = $_POST["searchByRut"] ?? '';如果你使用PHP7,或者$searchByRut = isset($_POST["searchByRut"]) ? $_POST["searchByRut"] : '';如果你
  • 非常感谢您的评论@ArtisticPhoenix,我正在努力解决这个问题。

标签: php mysql pagination


【解决方案1】:

感谢@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>

【讨论】:

    猜你喜欢
    • 2016-01-29
    • 2014-08-22
    • 1970-01-01
    • 2011-02-06
    • 2013-05-25
    • 2018-01-12
    • 2011-04-14
    • 2011-03-06
    • 1970-01-01
    相关资源
    最近更新 更多