上一个/下一个按钮?

时间:2012-05-03 16:59:54

标签: php mysql

我想为我所拥有的论坛输入上一个和下一个按钮,因为在论坛结束后,它超过了背景图像并且看起来不太好!有没有人知道一个简单的方法,或者我可以看到前一个和下一个按钮的东西?我想要它所以每页只限于每页5个帖子或其他东西。

如果代码有帮助的话,那就是代码。如果这是一个愚蠢的问题,我很抱歉。

<?php 
$dbc=mysql_connect('host','user','password','database') or die(mysql_error());
mysql_select_db('database',$dbc) or die(mysql_error());
?>

View Posts <br>
<form method="get" action="view_forum.php">
  <label>Select Weather to Filter </label><br />
  <select name="weather">
    <option value="all">all</option>
    <option value="cloudy">Cloudy</option>
    <option value="sunny">Sunny</option>
    <option value="windy">Windy</option>
    <option value="snowy">Snowy</option>
    <option value="mixy">Wintery Mix</option>
    <option value="rainy">Rainy</option>
  </select>
  <input type="submit" value="view" />
</form>

<div id="view">
 <center><img src="images/forum.png" width="589" height="97"></center>
</div>  
  <div id="white">
    <div id="blue">
      <div id="grey">
       <div id="container">
<?php
$weather = mysql_real_escape_string( $_GET["weather"] ); // keep your input clean

if ( $weather == "all" ) {
  $sql = "SELECT * FROM stories ORDER BY id DESC";
} else {
  $sql = "SELECT * FROM stories WHERE weather = '$weather' ORDER BY id DESC";
}

$result = mysql_query( $sql ) or die( mysql_error() );

while ( $row = mysql_fetch_assoc( $result ) ) {

    echo "<div class=\"names\"> {$row['name']}<br /></div>";
    echo "<div class=\"weathers\">{$row['weather']}<br /></div>";
   echo "<div class=\"stories\">{$row['story']}<br /></div>";



        echo "<img src=\"images/line.png\" width='800' height='3'>";

         echo "<br />"; 
}

?>
</div>
</div>
</div>
</div>

2 个答案:

答案 0 :(得分:2)

这很容易。您在请求中保留页面变量。如下图所示

if (!isset($_GET['page'])) {
   $page = 1;
} else {
   $page = (int)$_GET['page'];
}

在你的SQL语句中,你会放一些这样的东西,它使用页面变量来调整查询限制:

$query = 'SELECT * FROM someTable WHERE 1 LIMIT ' . (($page - 1) * $recordsPerPage) . ' ' . $recordsPerPage;

反正这样的东西。现在为您的上一个和下一个链接添加这样的内容,以便您可以递增/递减页面变量:

<? if ($page > 1) : ?>
   <a href="self.php?page=<?= $page - 1 ?>">Prev</a>
<? endif ?>
<? if ($page != $maxPages) : ?>
   <a href="self.php?page=<?= $page + 1 ?>">Next</a>
<? endif ?>

答案 1 :(得分:0)

你需要分页,在MySQL中你可以使用TOP:

-- Fist 10 results:
SELECT * FROM stories ORDER BY id DESC TOP 10 

-- 10 results from the number 11 (0 is the first)
SELECT * FROM stories ORDER BY id DESC TOP 10,10

-- 10 results from the number 50
SELECT * FROM stories ORDER BY id DESC TOP 50,10

要知道总结果,您可以使用SQL_CALC_FOUND_ROWS:

SELECT SQL_CALC_FOUND_ROWS as total, stories.* FROM stories ORDER BY id DESC TOP 10 

从PHP中,您可以计算分页:

$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;

if ($page < 1) $page = 1;

$sql = "SELECT SQL_CALC_FOUND_ROWS as total, stories.* FROM stories ORDER BY id DESC TOP " . ($page-1) .  ",10";