我正在尝试对由 MySQL 结果组成的数组进行分页。
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database: " . mysql_error());
if (isset($_GET['page']))
{
$page = $_GET['page'];
}
else
{
$page = 1;
}
$query = "SELECT * FROM blog";
$result = mysql_query($query);
$totalrows = mysql_num_rows($result);
$rowsperpage = 4;
$pages = ceil($totalrows / $rowsperpage);
$limit = 'LIMIT ' . ($page - 1) * $rowsperpage . ',' . $rowsperpage;
$query = "SELECT * FROM blog";
$result = mysql_query($query);
for ($j=0; $j < $totalrows; ++$j)
{
$results[] = mysql_fetch_array($result);
}
foreach($results as $id)
$sortAux[] = $id['id'];
array_multisort($sortAux, SORT_DESC, $results);
for ($j=0; $j < $rowsperpage; ++$j)
{
echo "<h1>" . $results[$j][0] . "</h1>";
echo "<hr />";
echo "<p>" . stripslashes(emoticons($results[$j][2])) . "</p>";
echo "<p style=\"font-size:12px;color:red;\">Posted at " . $results[$j][3] . " by " . $results[$j][1] . "</p>";
}
if ($page != $pages)
{
$nextpage = $page+1;
echo " <a href='{$_SERVER['PHP_SELF']}?page=$nextpage'>Older</a> ";
}
if ($page != 1)
{
$prevpage = $page-1;
echo " <a href='{$_SERVER['PHP_SELF']}?page=$prevpage'>Newer</a> ";
}
function emoticons ($text)
{
$emoticons = array(
":)" => "<img src='emoticons/12.png'>",
":(" => "<img src='emoticons/13.png'>",
";)" => "<img src='emoticons/4.png'>",
":D" => "<img src='emoticons/7.png'>",
":P" => "<img src='emoticons/10.png'>",
"<3" => "<img src='emoticons/3.png'>",
);
return str_replace(
array_keys($emoticons),
$emoticons,
$text);
}
?>
问题是for循环。我不知道如何从每个页面获得 4 个不同的结果。顺便说一下,它需要从最新到最旧进行排序。这就是我使用array_multisort 的原因。谢谢。
注意:我知道我需要升级到 mysqli,但现在我使用的是旧的 mysql_*。