gpt4 book ai didi

PHP 数组分页

转载 作者:行者123 更新时间:2023-11-29 00:41:22 27 4
gpt4 key购买 nike

我正在尝试对由 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_*。

最佳答案

来吧!你已经有了正确的 SQL 代码片段......

您首先将第一个查询更改为 'SELECT COUNT(*) FROM blog' 并结合 $x = mysql_fetch_array($result); $totalrows = $x[0];

然后启动分页 SQL 查询:

$limit = 'LIMIT ' . ($page - 1) * $rowsperpage . ',' . $rowsperpage;
$query = "SELECT * FROM blog ORDER BY id DESC {$limit}";

删除 multisort-thingy 等

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com