Answer the question
In order to leave comments, you need to log in
How to do pagination?
I have a database where projects are located, and there is navigation through these projects on the page using two buttons "Forward" and "Back"
<?php
$nextpost = next_post($post_id);
$prevpost = prev_post($post_id);
?>
<div>
<a href="/project?post_id=<?= $prevpost['id'] ?>"><button>Prev</button></a>
<a href="/project?post_id=<?= $nextpost['id'] ?>"><button">Next</button></a>
</div>
function next_post($post_id)
{
global $link;
$sql = "SELECT * FROM projects WHERE id > " . $post_id . " ORDER BY id ASC LIMIT 1";
$result = mysqli_query($link, $sql);
$nextpost = mysqli_fetch_assoc($result);
return $nextpost;
}
function prev_post($post_id)
{
global $link;
$sql = "SELECT * FROM projects WHERE id < " . $post_id . " ORDER BY id DESC LIMIT 1";
$result = mysqli_query($link, $sql);
$prevpost = mysqli_fetch_assoc($result);
return $prevpost;
}
Answer the question
In order to leave comments, you need to log in
It's not clear from the code below what happens.
if, for example, I am on a project with id=5 (and id=6 does not yet exist) and at the same time I click on the "Forward" button, then I am transferred to a page with id=6, which does not exist and I just get an error.
Gods of clean code forgive me.
/**
* Следующий пост
*
* @param $post_id
*
* @return string[]|null
*/
function next_post($post_id)
{
global $link;
$sql = "SELECT * FROM projects WHERE id > " . $post_id . " ORDER BY id ASC LIMIT 1";
$result = mysqli_query($link, $sql);
$nextpost = mysqli_fetch_assoc($result);
if (!$nextpost) {
return first_post();
}
return $nextpost;
}
/**
* Предыдущий пост
*
* @param $post_id
*
* @return string[]|null
*/
function prev_post($post_id)
{
global $link;
$sql = "SELECT * FROM projects WHERE id < " . $post_id . " ORDER BY id DESC LIMIT 1";
$result = mysqli_query($link, $sql);
$prevpost = mysqli_fetch_assoc($result);
if (!$prevpost) {
return last_post();
}
return $prevpost;
}
/**
* Первый пост
*
* @return string[]|null
*/
function first_post()
{
global $link;
$sql = "SELECT * FROM projects WHERE ORDER BY id ASC LIMIT 1";
$result = mysqli_query($link, $sql);
$post = mysqli_fetch_assoc($result);
return $post;
}
/**
* Последний пост
*
* @return string[]|null
*/
function last_post()
{
global $link;
$sql = "SELECT * FROM projects WHERE ORDER BY id DESC LIMIT 1";
$result = mysqli_query($link, $sql);
$post = mysqli_fetch_assoc($result);
return $post;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question