phpmysqlpaginationnumbers

How to display each number of a variable?


basically what I want is display a count until it reaches a certain number, so if I had the number "5" on the screen it would show "1 2 3 4 5". Or if I had the number "3" it would show "1 2 3".

The reason is because im creating a paging system for my MySQL results. The code I have so far is

$result1 = mysql_query("SELECT * FROM questions WHERE subcat = '$conditions'");
$num_rows = mysql_num_rows($result1);
$results_per_page = "3";
$num_pages = $num_rows / $results_per_page;

So it counts how many results there are, for example we will say 12 results. It then devides this number by how many results I want shown per page. In this example its "3". So the answer is "4". So I now want to have "1 2 3 4" displayed on the screen, however I want each number to be a link.

How do I do this?

Thanks Ben


Solution

  • foreach( range( 1, $num_pages) as $i) {
        echo '<a href="index.php?page=' . $i . '">' . $i . '</a>';
    }
    

    Or, an approach suggested by knittl:

    echo implode( ' | ', array_map( function( $i) {
        return sprintf( '<a href="index.php?page=%d">%d</a>', $i, $i);
    }, range( 1, $num_pages)));
    

    Prints something like this:

    1 | 2 | 3 | 4 | 5