<? /* Скрипт показывает значения таблицы*/ $hostname = "--"; $username = "--"; $password = "--"; $dbName = "--"; /* Таблица MySQL, в которой хранятся данные */ $userstable = "gm_bans"; /* создать соединение */ MYSQL_CONNECT($hostname,$username,$password) OR DIE("Не могу создать соединение "); @mysql_select_db("$dbName") or die("Не могу выбрать базу данных "); /*Кодировка*/ mysql_query("SET NAMES 'utf8'"); mysql_query("SET CHARACTER SET 'utf8'"); mysql_query("SET SESSION collation_connection = 'utf8_general_ci'"); /* Выбрать все записи */ $query = "SELECT * FROM $userstable"; $result = MYSQL_QUERY($query); $users_on_page="5"; $count=mysql_fetch_array(mysql_query("select count(id) from `$userstable`")); /* Количество*/ $number = MYSQL_NUMROWS($result); /* Напечатать всех в красивом виде*/ $i = 1; IF ($number == 0) { PRINT "<CENTER><P>Нет результатов</CENTER>"; } ELSEIF ($number > 0) { PRINT "<CENTER><P>Количество: $number"; PRINT "<table class='bordered bordered2'>"; PRINT "<TR><TD>Ник игрока</TD><TD>Причина</TD><TD>Ник администратора</TD><TD>Срок бана</TD></TR>"; WHILE ($i < $number){ $player_nick = mysql_result($result,$i,"player_nick"); $ban_reason= mysql_result($result,$i,"ban_reason"); $admin_nick= mysql_result($result,$i,"admin_nick"); $ban_length = mysql_result($result,$i,"ban_length"); if($ban_length == "0"){ PRINT "<TR><TD>$player_nick</TD><TD>$ban_reason</TD><TD>$admin_nick</TD><TD>Навсегда</TD></TR>"; } else{ PRINT "<TR><TD>$player_nick</TD><TD>$ban_reason</TD><TD>$admin_nick</TD><TD>$ban_length</TD></TR>"; }; $i++; } PRINT "</table>"; PRINT "</CENTER>"; } ?> 

Help please make page navigation, 4 examples have already tried fail

Closed due to the fact that off-topic participants Dmitriy Simushev , zRrr , cheops , Nicolas Chabanovsky 13 May '16 at 7:01 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • “Questions asking for help with debugging (“ why does this code not work? ”) Should include the desired behavior, a specific problem or error, and a minimum code for playing it right in the question . Questions without an explicit description of the problem are useless for other visitors. See How to create minimal, self-sufficient and reproducible example . " - Dmitriy Simushev, zRrr, cheops
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • $ users_on_page = "5"; $ count = mysql_fetch_array (mysql_query ("select count (id) from $userstable ")); Extra lines - Egor
  • Stop using mysql_ *. It has been removed from PHP version 7.0. Learn to write code in one register (lower). - E_p
  • Thanks for the help - Egor
  • According to community rules, questions should not be reduced to completing tasks for students. Give an example of your implementation and ask a question describing specific problems. - Nicolas Chabanovsky

2 answers 2

The simplest thing you can use for paginated output is LIMIT . As if for this and done.

 $query = "SELECT * FROM $userstable ORDER BY player_nick, admin_nick, ban_reason, ban_length LIMIT $offset, $page_size"; $countQuery = "SELECT count(*) FROM $userstable; 

$offset - The most important and complex parameter in this case. It determines which page will be displayed in HTML.
The database server skips the first $offset lines (and) selected by the query and starts issuing results starting at line number $offset + 1 .
$page_size - the number of entries on the page. probably the same as your $users_on_page .
The server will result in no more than this number of rows.

It is important to be ORDER BY . The order should be so that it does not happen that the same lines will be on the first, then on the tenth page.

Page number is calculated by $offset and $page_size :
$page_number = $offset % $page_size . Like so.
You can also determine the required offset by the page number:
$offset = ($page_number - 1) * $page_size number of pages is obtained from the query $countQuery and $page_size :
$page_count = ($count / $page_size) + (($count % $page_size) == 0 ? 0 : 1)

The necessary navigation buttons / links are formed. $page_number (from 1 to $page_count ) is used in the title. We must somehow show the page number.
The calculated $offset used as a parameter that will be passed back to the server when the button is pressed.
In your example, there are no page navigation elements and I will not invent anything. The idea is clear.

     <?php // Будем выводить по 2 записи на листе: $number = 2; // Читаем сдвиг из GET-массива: $offset = isset($_GET['offset']) ? (int)$_GET['offset'] : 0; // Коннект до базы данных $link = mysql_connect('localhost', 'root', ''); if (!$link) die('Не могу соединиться с базой данных'); // Выбираем базу данных mysql_select_db('paginator', $link); // Выполняем запрос 'посчитать число записей' $result = mysql_query("SELECT COUNT(*) FROM `table`", $link); // Теперь в переменной $total общее число записей $total = mysql_result($result, 0); $menu = getMenuofPages($total, $number, $offset); ?> <? function getMenuofPages($total, $number, $offset) { // Подфункция определяет есть ли уже в текущем url get-данные // и дописывает соответственно нужный offset: function getGoodUrl($url, $cur) { if ($_SERVER['QUERY_STRING'] == "") { return $url."?offset=".$cur; }else { if (substr_count($_SERVER['QUERY_STRING'], "offset=") > 0) { $url = preg_replace("/offset=\d+/i", "offset=".$cur, $url); return $url; }else { return $url."&offset=".$cur; } } } // Если общее число меньше числа записей, которые мы должны вывести на // странице, то ничего не делаем: if ($total <= $number) { return; } $url = $_SERVER['REQUEST_URI']; $int = intval($total / $number); // Целая часть от деления $rest = $total % $number; // Остаток от деления $menu = ""; // Сначала перебираем целые части for ($i = 0; $i < $int; $i++) { $cur = $i * $number; if ($cur == $offset) { // Проверка на текущую страницу $menu .= " ".($cur + 1)."-".($cur + $number); }else { $menu .= " <a href=\"".getGoodUrl($url, $cur)."\">". ($cur + 1)."-".($cur + $number)."</a>"; } } // Потом остаток (если есть) if ($rest > 0) { $cur += $number; if ($cur == $offset) { // Проверка на текущую страницу if ($rest == 1) { $menu .= " ".($cur + 1)." "; }else { $menu .= " ".($cur + 1)."-".($cur + $rest)." "; // | } }else { if ($rest == 1) { $menu .= " <a href=\"".getGoodUrl($url, $cur)."\">".($cur + 1)."</a> "; //| }else { $menu .= " <a href=\"".getGoodUrl($url, $cur)."\">". ($cur + 1)."-".($cur + $rest)."</a> "; //| } } }else { $menu .= " "; } return $menu; } ?> <? // Читаем из базы $number записей начиная с $offset: $result = mysql_query("SELECT * FROM `table` LIMIT $offset, $number", $link); // Распечатываем результат вывода пагинации: echo '<div class="pagination">'; echo $menu; echo '</div>'; while ($row = mysql_fetch_assoc($result)) {?> <div class="center" style="background:#fefefe; margin:20px auto;"> <h3> <span style="padding:0 10px;background:red;"><?=$row['id'];?></span> <span style="padding:0 5px; background:yellow;"><?= $row['autor'];?></span> <span style="padding:0 4px; background:lightblue;"><?= $row['date'];?></span> </h3> <p> <?= $row['text']; ?> </p> </div> <?}?> <div class="pagination"> <? echo $menu ?> </div> 

    something like this