Help please solve this problem. We have a DBMS with data and indexing by ID, and it happens that IDs are not arranged in order (records are deleted), that is, I use the mysql fetch array to output all records before the pulse is lost through while. And how can I limit the output of mysql fetch array through a while, say 50 first entries? And how can we take the second set of 50 entries, the third?
5 answers
Если нужен постраничный вывод, то можно сделать так: $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); // Переменная хранит число сообщений выводимых на станице $num = 50; // Извлекаем из URL текущую страницу $page = $_GET['page']; // Определяем общее число сообщений в базе данных $query1 = "SELECT * FROM Имя базы данных"; $result = mysqli_query($dbc, $query1); $posts = mysqli_num_rows($result); // Находим общее число страниц $total = intval(($posts - 1) / $num) + 1; // Определяем начало сообщений для текущей страницы $page = intval($page); // Если значение $page меньше единицы или отрицательно // переходим на первую страницу // А если слишком большое, то переходим на последнюю if(empty($page) or $page < 0) $page = 1; if($page > $total) $page = $total; // Вычисляем начиная к какого номера // следует выводить сообщения $start = $page * $num - $num; $query = "SELECT * FROM Имя базы данных WHERE ORDER BY id ASC LIMIT $start, $num"; $data = mysqli_query($dbc, $query); ... // Проверяем нужны ли стрелки назад if ($page != 1) $pervpage = '<a href=' . $_SERVER['PHP_SELF'] . '?page=1><<</a> <a href=' . $_SERVER['PHP_SELF'] . '?page='. ($page - 1) .'><</a> '; // Проверяем нужны ли стрелки вперед if ($page != $total) $nextpage = ' <a href=' . $_SERVER['PHP_SELF'] . '?page='. ($page + 1) .'>></a> <a href=' . $_SERVER['PHP_SELF'] . '?page=' .$total. '>>></a>'; // Находим две ближайшие станицы с обоих краев, если они есть if($page - 2 > 0) $page2left = ' <a href=' . $_SERVER['PHP_SELF'] . '?page='. ($page - 2) .'>'. ($page - 2) .'</a> | '; if($page - 1 > 0) $page1left = '<a href=' . $_SERVER['PHP_SELF'] . '?page='. ($page - 1) .'>'. ($page - 1) .'</a> | '; if($page + 2 <= $total) $page2right = ' | <a href=' . $_SERVER['PHP_SELF'] . '?page='. ($page + 2) .'>'. ($page + 2) .'</a>'; if($page + 1 <= $total) $page1right = ' | <a href=' . $_SERVER['PHP_SELF'] . '?page='. ($page + 1) .'>'. ($page + 1) .'</a>'; // Вывод меню echo $pervpage.$page2left.$page1left.'<b>'.$page.'</b>'.$page1right.$page2right.$nextpage; mysqli_close($dbc); SELECT * FROM таблица ORDER BY id ASC LIMIT номер_страницы*50,50; Where
ORDER BY id ASC - sort by id.
UPD. Pagination naturally starts from scratch.
обычно делают с помощю GET запроса. Например, у вас 10к вопросов, то берете лимитом 50 первых записей, при условий что нет !isset($page). В противном случае `select * from .... where ... limit $page*50,50;` Не забываем еще, про количестве "отображаемых",соседних страниц... SELECT * FROM table ORDER BY id ASC LIMIT ( page_number-1 ) * 50.50;
use the solution that is typical for all large projects.
there is no paginated output based on OFFSET, LIMIT, because It has several significant drawbacks:
- cannot be used on samples with a large offset offset, too much data is captured in the request.
- if the data is frequently updated, then it may happen that when new data is loaded, it will already have been previously output.
it is better to use a sample with an offset by id or date (solution for displaying the most recent entries by ID):
SELECT * FROM table WHERE id < offset ORDER BY id DESC LIMIT 50; at the start of offset make the maximum possible for this column (if INT, then 4294967295). then send the minimum ID value from the current selection in the request and the next time it returns as a new offset.
the same applies to the date column if the data is ordered by date, and the IDs are not in chronological order.
Also, do not forget to use indexes (for simple queries with date, an index on this column, for complex queries with several conditions, we make a composite index strictly in the order of the WHERE and ORDER BY conditions, for example (cond_1, cond_2, date)).