2017-12-21 10 views
1

私は他の投稿を見てきましたが、私がやっていることに似ていますが、私が間違っていることを理解できないようです。私は5/n結果を表示する必要があります。ここで、n =はSQLクエリからの合計です。私は他の人が何を提案したかを試してみましたが、何らかの理由で私は本当に奇妙な結果を得ています。問題を解決できないようです。ページあたりのPHPの表示

$sqlPosts = "SELECT 
       count(post_owner) 
       FROM post_table"; 

    $stmt = $db -> prepare($sqlPosts); 
    $stmt->execute(); 
    $stmt->store_result(); 
    $stmt->bind_result($totalPosts); 
    $stmt->fetch(); 

    $sql = "SELECT 
       body_of_post, 
       date_time, 
       post_owner, 
       title, 
       id 
      FROM 
       post_table 
      ORDER BY 
       date_time 
      DESC LIMIT 
       ?,?"; 
    $sqlFive = 5; 
    $sqlTotal = $totalPosts/$sqlFive; 
    $page = ($page - 1) * $limit; 
    $stmt = $db -> prepare($sql); 
    $stmt->bind_param('dd',$sqlFive, $sqlTotal); 
    $stmt->execute(); 
    $stmt->store_result(); 
    $stmt->bind_result($body_of_post, $date_time, $post_owner, $title, $id); 

    echo "<p> Number of results found: ".(($stmt->num_rows)/2)."/".$stmt->num_rows."</p>"; 
    echo '<a href=\"index.php?page='.$page.'\">Next '.$page.'</a>'; 

これは私が得る結果である:

見出された結果の数:1/2

次0

それは、代わりにこのようにする必要があります:結果の

数found:5/10

次5

誰かが私が間違ってやっていることを説明してください、そしてこれをどのように修正するのでしょうか?また、クエリでOFFSETを使用する方が簡単でしょうか?

+0

'$ totalPosts'はあなたを与えたんか? '$ page'と' $ limit'の宣言はどこにありますか?必要なコードをすべて入力してください – Erwin

答えて

2

あなたは情報を取得し、表示するために間違った変数を使用している:

//I'm assuming that $page exists somewhere before the code you posted 
.... 
$rowsPerPage = 5; //renamed for clarity 
$totalPages = ceil($totalPosts/$rowsPerPage); //we need to round this value up 
$offset  = ($page - 1) * $rowsPerPage; //e.g. on $page=2 we need an offset of five rows. Renamed for clarity 
$stmt  = $db->prepare($sql); 
$stmt->bind_param('dd', $offset, $rowsPerPage); //OFFSET comes first when using comma notation 
$stmt->execute(); 

$totalPostsOnThisPage = $stmt->num_rows; //to make things clear 
//You could also show ($offset + 1) . '-' . ($offset + $totalPostsOnThisPage) . ' of ' . $totalPosts --- output: 6-10 of 10 
echo "<p> Number of results found: ". $totalRowsOnThisPage . "/" . $totalPosts ."</p>"; 
//display next only if has more posts 
if ($page < $totalPages) { 

    echo '<a href=\"index.php?page='.$page.'\">Next '. $rowsPerPage .'</a>'; 
} 
+0

はい、ページは1に等しい – Pachuca

関連する問題