【问题标题】:php sql results with pagination带分页的php sql结果
【发布时间】:2012-05-02 06:45:05
【问题描述】:

我一直在做一些代码,这些代码基本上从 mysql 中提取数据并通过 php 显示。结果在页面上一次显示 3 个,我从来没有遇到过任何问题。

我最近在数据库项目中添加了一个字段:“已售罄”和“有货”,并且正在尝试(悲惨地)进行两次搜索 - 首先我想显示有库存的项目,然后是那些已售罄。不幸的是,我多年来使用的分页代码不喜欢我运行两个 php 查询,而只是在页面中添加 3 个额外的项目(如果适用)。

完整代码为:

        <form name="form1" method="get" action="products.php">
            <?php 
      if(!empty($msg)) {
      echo $msg[0];
      }
      ?>



             <input name="q" class="textInput2" input type="search" id="q" placeholder="search image name..." autosave="applestyle_srch" results="5" onKeyUp="applesearch.onChange('srch_fld','srch_clear')" />     


              <input name="doSearch" type="hidden" id="doSearch2" value="Search">


        <?php if ($get['doSearch'] == 'Search') {
      // find out how many rows are in the table 
$sql = "SELECT COUNT(*) FROM products";
$result = mysql_query($sql) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];

// number of rows to show per page
$rowsperpage = 3;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);

// 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;
} // end if

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

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


      if($get['q'] == '') {  
    $sql = "SELECT * FROM products WHERE status='sold' ORDER BY `price` ASC LIMIT $offset, $rowsperpage";
      } 
      else { 
      $sql = "select * from products where `title` like '%$_REQUEST[q]%' LIMIT $offset, $rowsperpage";
      }

$result1 = mysql_query($sql) or trigger_error("SQL", E_USER_ERROR);


       if($get['q'] == '') {  
    $sql = "SELECT * FROM products WHERE status='in stock' ORDER BY `price` ASC LIMIT $offset, $rowsperpage";
      } 
      else { 
      $sql = "select * from products where `title` like '%$_REQUEST[q]%' LIMIT $offset, $rowsperpage";
      }

$result2 = mysql_query($sql) or trigger_error("SQL", E_USER_ERROR);


      ?></form></div>
 <div id="pagination" style="float:right; display:inline; margin-right:10px;">
          page:<?php

/******  build the pagination links ******/
// if not on page 1, don't show back links
if ($currentpage > 1) {
   // show << link to go back to page 1
   echo " <a href='{$_SERVER['PHP_SELF']}?q=&doSearch=Search&currentpage=1'><<</a> ";
   // get previous page num
   $prevpage = $currentpage - 1;
   // show < link to go back to 1 page
   echo " <a href='{$_SERVER['PHP_SELF']}?q=&doSearch=Search&currentpage=$prevpage'><</a> ";
} // end if
      // range of num links to show
$range = 3;

// 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
         echo " [<b>$x</b>] ";
      // if not current page...
      } else {
         // make it a link
         echo " <a href='{$_SERVER['PHP_SELF']}?q=&doSearch=Search&currentpage=$x'>$x</a> ";
      } // end else
   } // end if 
} // end for

// 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 
   echo " <a href='{$_SERVER['PHP_SELF']}?q=&doSearch=Search&currentpage=$nextpage'>></a> ";
   // echo forward link for lastpage
   echo " <a href='{$_SERVER['PHP_SELF']}?q=&doSearch=Search&currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
?>
          </div>

    </div>
    </div>


</div></p>


<div class="category-products">


  <form name "searchform" action="products.php" method="post">

   <?php while($rrows = mysql_fetch_array($result2))
{
    echo '<div><div id="searchimage"><a class="product-image" href="productspec.php?productcode=' . $rrows['productcode'] . '" title="' . $rrows['title'] . '">';
    echo '<img src="' . $rrows['photo'] . '" width="225" height="150" alt="" title="' . $rrows['title'] . '" /></a></div>';
    echo '<div id="searchdetails">
<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>
    <td height="30"><h3 class="product-name"><a href="productspec.php?productcode=' . $rrows['productcode'] . '" title="' . $rrows['title'] . '">' . $rrows['title'] . '</a></h3>';
    echo '</td>
  </tr>
  <tr>
    <td>' . $rrows['desc'] . '';
    echo '</td>
  </tr>
   <tr>
    <td><h3 class="price">&pound;' . $rrows['price'] . '&nbsp;' . $rrows['pandp'] . '</h3>'; echo '</td>
  </tr>
</table></div>';
echo '</div>';
}
?>

 <?php while($rrows = mysql_fetch_array($result1))
{
    echo '<div><div id="searchimage"><a class="product-image" href="productspec.php?productcode=' . $rrows['productcode'] . '" title="' . $rrows['title'] . '">';
    echo '<img src="' . $rrows['photo'] . '" width="225" height="150" alt="" title="' . $rrows['title'] . '" /><img src="soldout.png" id="soldout" /></a></div>';
    echo '<div id="searchdetails">
<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>
    <td height="30"><h3 class="product-name"><a href="productspec.php?productcode=' . $rrows['productcode'] . '" title="' . $rrows['title'] . '">' . $rrows['title'] . '</a></h3>';
    echo '</td>
  </tr>
  <tr>
    <td>' . $rrows['desc'] . '';
    echo '</td>
  </tr>
   <tr>
    <td><h3 class="price">&pound;' . $rrows['price'] . '&nbsp;' . $rrows['pandp'] . '</h3>'; echo '</td>
  </tr>
</table></div>';
echo '</div>';
}
?>

  </form> <?php } ?>

我完全可以理解代码可以更简洁 - (我多年来一直没有修改分页过程,因为它一直有效) - 但我假设必须有一种更简单的方法来显示表格中的所有项目无需同时运行 $result1 和 $result2 查询。

非常感谢任何帮助!

京东

【问题讨论】:

    标签: php mysql pagination


    【解决方案1】:

    这是我为已编程的电路板制作的功能。我希望这对您有所帮助。 由于我有一段时间没有更新,所以(对我来说)有点乱。

    此函数要求的 5 个必需变量是行数、页面的 url,以便链接正常工作,“每页帖子”基本上意味着每页需要多少个结果(默认 20),链接的名称,因此如果您希望下一页出现在页面链接上,最后如果您想更改要更改页面的 $_GET。默认为 $_GET['page']。

      function pagelinks($numrows, $primaryurl, $ppp=20, $aname="", $getpage="default")
       {
        global $baseurl; //this is for something like http://somesite.com/
    
        //If the GET method is not defined, $_GET[page] is used.
       if ($getpage == "default")
        {
         $page = intval($_GET['page']);
         $getpage = "page";
        }
       else
        {
         $page = intval($_GET[$getpage]);
        }
        $ppp = intval($ppp);
    
       if ($aname != "")
        {
         $linkname = "#$aname";
         //$linkname2 = "<a name=\"next_page\"></a>";
        }
    
        //If we don't define the posts/articles per page, we go to a postsperpage user default.
       if ($ppp == 0)
        {
         $ppp = 20;
        }
    
        //If the page is negative, we define it 1.
       if (intval($page) < 0)
        {
         $page = 1;
        }
    
        //If the GET page is higher than the highest possible, we make it the highest limiting page.
       if (($numrows / $ppp + 1) < intval($page))
        {
         $page = intval($numrows / $ppp + 1);
        }
    
        //If the url doesn't point to any page, we just set it to the first group of the query limit.
       if (!$page)
        {
         $page = 1;
        }
        $min = (($page - 1) * $ppp);
        $maxnum = floor($numrows / $ppp);
        $pages = "<center><small>Pages:</small><br>";
        //If we are on the first page, don't link to any previous pages because there are none
        //Else we link the arrow to the page one less than current.
       if (($page - 1) <= 0)
        {
         $pages .= "<img src=\"$baseurl/boardfiles/images/previous_mono.gif\" border=\"0\" alt=\"\">";
        }
       else
        {
         $pages .= "<a href=\"".$primaryurl."&amp;$getpage=".($page-1)."$linkname\"><img src=\"$baseurl/boardfiles/images/previous.gif\" border=\"0\" alt=\"<\"></a>";
        }
       for ($i = 0; $i <= $maxnum; $i++)
        {
         $i2 = $i+1;
        if ($i != $maxnum || ($numrows / $ppp) != (floor($numrows / $ppp)) || !$numrows)
         {
          //If the page number matches our page, it isn't linked.
          //Else we keep linking all existing page numbers.
         if ($page == $i2)
          {
           $pages .= " $i2";
          }
         else
          {
           $pages .= " <a href=\"".$primaryurl."&amp;$getpage=".($i + 1)."$linkname\">".($i + 1)."</a>";
          }
         }
        else
         {
          $lastcutoff = 1;
         }
        }
        //If we are on the last page, don't link to the next page because we are on the top one.
        //Else we link the arrow to the page one more than current.
       if ($page > $maxnum || ($lastcutoff && $page > $maxnum - 1))
        {
         $pages .= " <img src=\"$baseurl/boardfiles/images/next_mono.gif\" border=\"0\" alt=\"\">";
        }
       else
        {
         $pages .= " <a href=\"".$primaryurl."&amp;$getpage=".($page+1)."$linkname\"><img src=\"$baseurl/boardfiles/images/next.gif\" border=\"0\" alt=\">\"></a>";
        }
        $pages .= "</center>";
        $return['pages'] = $pages;
        $return['querylimit'] = " LIMIT $min, $ppp";
        $return['min'] = $min; //Used in users.php
        return $return;
       }
    

    现在您需要稍微更改代码以满足您的需要,但接下来您需要将其放入查询中。下面是一些使用示例:

      #-- Page Stuff --#  
      $articlesperpage = 10;
      $numrows = $misc['totalarticles'];
    
      $p = pagelinks($numrows, "$baseurl/?p=news", $articlesperpage);
      $pages = $p['pages'];
      #-- Page Stuff --#  
    
      $allnews = sql_query("SELECT * FROM `news` ORDER BY `id` DESC$p[querylimit]");
    

    重要的是使用 $p[querylimit] 来限制您的查询并使用 $pages 作为分页链接。希望这有用!




    编辑:我最近还创建了另一个您可能想要的分页功能,而不是上面的功能,因为这个功能使用选择选项列表而不是一堆链接。我还修复了一个小时前注意到的错误。有趣的是,当我再次检查时,我是如何抓住它的。

      function pagination2($numrows, $primaryurl, $ppp=20)
       {
        global $baseurl;
    
        $page = intval($_GET['page']);
        $ppp = intval($ppp);
    
        //If we don't define the posts/articles per page, we go to a postsperpage user default.
       if ($ppp == 0)
        {
         $ppp = 20;
        }
    
        //If the page is negative, we define it 1.
       if (intval($page) < 0)
        {
         $page = 1;
        }
    
        //If the GET page is higher than the highest possible, we make it the highest limiting page.
       if (($numrows / $ppp) < intval($page))
        {
         $page = intval($numrows / $ppp);
        }
    
        //If the url doesn't point to any page, we just set it to the first group of the query limit.
       if (!$page)
        {
         $page = 1;
        }
        $min = (($page - 1) * $ppp);
        $maxnum = floor($numrows / $ppp);
    
        $pages = "<select onchange=\"window.location.href=this.value;\" style=\"font-size: 8pt;\">";
    
       for ($i = 0; $i <= $maxnum; $i++)
        {
         $i2 = $i + 1;
        if ($i != $maxnum || ($numrows / $ppp) != (floor($numrows / $ppp)) || !$numrows)
         {
         if ($page == $i2)
          {
           $pages .= "<option value=\"$primaryurl&amp;page=$i2\" selected>Page $i2</option>";
          }
         else
          {
           $pages .= "<option value=\"$primaryurl&amp;page=$i2\">Page $i2</option>";
          }
         }
        }
    
        $pages .= "</select>";
    
    
        $return['pages'] = $pages;
        $return['querylimit'] = " LIMIT $min, $ppp";
        $return['min'] = $min; //Used in users.php
        return $return;
       }
    

    【讨论】:

      猜你喜欢
      • 2012-05-19
      • 2012-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-05
      • 2011-06-30
      • 1970-01-01
      相关资源
      最近更新 更多