1

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_* を使用しています。

4

1 に答える 1

1

おい!そこにはすでに正しいSQLコードのフラグメントがあります...

最初に、最初のクエリを「SELECT COUNT(*)FROMblog」に変更します。$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などを削除します。

于 2012-08-26T10:01:07.093 に答える