I am trying to paginate an array made of MySQL results.
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);
}
?>
The problem is the for loop. I can’t figure out on how to get 4 different results from each page. By the way it needs to be sorted from newest to oldest. That’s why I used array_multisort. Thanks.
Note: I know I need to upgrade to mysqli but for now I’m using the old mysql_*.
c’mon! you have fragments of the correct SQL-Code in there already…
you have FIRST change the first query to ‘SELECT COUNT(*) FROM blog’ in combination with
$x = mysql_fetch_array($result); $totalrows = $x[0];and then fire up the paginated SQL-query:
remove the multisort-thingy etc.