Timothy Fisher Timothy Fisher - 4 months ago 9
PHP Question

Creating pagination links with search parameters

I want to know how to approach implementing pagination with user input as search parameters. I understand the basics of pagination without user input and have no trouble doing that, it's when user input comes in that it confuses me. I don't know how to make the page-number links use the correct query based on what has been searched.

For example the basic idea:

HTML

<input type="text" name="id" placeholder="ID">
<input type="text" name="name" placeholder="Name">
<button id="btn_search">Search</button>

<div id="search_results"></div>


JS

$("#btn_search").on('click', function() {
$.ajax({
url: 'process.php',
type: 'POST',
data: {id: $("input[name=id]").val(), name: $("input[name=name]").val()},
success: function(result) {
$("#search_results").html(result);
}
});
});


PHP

// Grab submitted search parameters and store in variable
if (isset($_POST["id"]) && !empty($_POST["id"])) {
$id = $_POST["id"];
} else {
$id = null;
}
if (isset($_POST["name"]) && !empty($_POST["name"])) {
$name = $_POST["name"];
} else {
$name = null;
}
$count_query = "SELECT COUNT(*) FROM users";
// Code here to get total row count for pagination
$query = "SELECT * FROM users WHERE id = ? AND name = ?";
$stmt = $connection->prepare($query);
$stmt->bind_param('is', $id, $name);
$stmt->execute();
// Dump as table


I'm thinking the right approach is something like this:

<ul class="pagination">
<li><a href="paginate.php?id=<?php echo $id; ?>&name=<?php echo $name; ?>"></a></li>
<li><a href="paginate.php?id=<?php echo $id; ?>&name=<?php echo $name; ?>"></a></li>
</ul>


And then include one more parameter for the page number via a for loop.

Is it safe to do this with some client-side input validation? And do I have a valid approach?

EDIT

Naveed's answer was helpful so I'll mark it as answered. This article: https://jadendreamer.wordpress.com/2012/11/20/php-tutorial-searching-and-pagination/ helped me out a lot with understanding how to do this. It is old but explains everything well. I ended up using the tags to pass back the query parameters.

Answer

You need to set few variables as hidden in form.

Number of records per page

Offset of records

Then you need to get number of pages and generate links in HTML

In PHP file :

$return['total'] = $rs->num_rows;
$return['records']=$rs;
echo json_encode($return);

<ul>
    <li><a href="#2" class="pagination">2</a></li>
    <li><a href="#3" class="pagination">3</a></li>
</ul>

Then in JQuery

$('a.pagination').click(function(){
    var page = $(this).attr('href').replace('#', '');
    // now here you need to get data from process.php and pass the page variables or calculate the offset like page 2 seems offset 21 to 40 based on limit
});