Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Sep 2012
    Posts
    87
    Thanks
    18
    Thanked 0 Times in 0 Posts

    Exclamation This PHP Code is not working as intended, why?

    What's wrong with the code below which is not producing the intended results. It's displaying all the titles in every page.
    I'd like the php code to list the first twenty titles from a table in a database on page 1, the next twenty in page 2, the next twenty in page 3....and so on.

    Code:
     <?php
    $page = (int) $_GET['page'];
    if ($page < 1) $page = 1;
    
    // Include database connection settings
          include('config.inc');
    
    $numberOfPages = 100;
    $resultsPerPage = 20;
    $startResults = ($page - 1) * $resultsPerPage;
    $numberOfRows = mysql_num_rows(mysql_query('SELECT Title FROM entries'));
    $totalPages = ceil($numberOfRows / $resultsPerPage);
    
    $query = mysql_query("SELECT * FROM entries") or die ('Error: '.mysql_error ()); 
    
    while ($output = mysql_fetch_array($query)){ 
        echo '<a href="selected_post.php?Index='.$output['Index'].'">' .$output['Title'].'</a><br>'; 
    }
    
    $halfPages = floor($numberOfPages / 2);
    $range = array('start' => 1, 'end' => $totalPages);
    $isEven = ($numberOfPages % 2 == 0);
    $atRangeEnd = $totalPages - $halfPages;
    
    if($isEven) $atRangeEnd++;
    
    if($totalPages > $numberOfPages)
    {
    	if($page <= $halfPages)
    		$range['end'] = $numberOfPages;
    	elseif ($page >= $atRangeEnd)
    		$range['start'] = $totalPages - $numberOfPages + 1;
    	else
    	{
    		$range['start'] = $page - $halfPages;
    		$range['end'] = $page + $halfPages;
    		if($isEven) $range['end']--;
    	}
    }
    
    if($page > 1)
    	echo '<a href="?page='.($page - 1).'">&laquo;</a>&nbsp';
    
    for ($i = $range['start']; $i <= $range['end']; $i++)
    {
    	if($i == $page)
    		echo '<strong>'.$i.'</strong>&nbsp;';
    	else
    		echo '<a href="?page='.$i.'">'.$i.'</a>&nbsp;';
    }
    if ($page < $totalPages)
    	echo '<a href="?page='.($page + 1).'">&raquo;</a>&nbsp;';
    ?>

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,978
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    There's no LIMIT call on your query. So ever page will query for every record.
    You need to add the limit to the query: LIMIT $startResults, $resultsPerPage.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • Users who have thanked Fou-Lu for this post:

    Thuita Maina (03-22-2013)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •