Search MySQLi database with pagination using PHP

January 19, 2024


$search_string = 'something....';
$max_results_per_page = 30;
$page = 1;

$query = "
SELECT count(id) AS number_of_items
FROM items
WHERE deleted != 'y'
AND ( keywords LIKE CONCAT('%',?,'%') OR title LIKE CONCAT('%',?,'%') )
";

$stmt = $mysqli -> prepare($query);
$stmt -> bind_param( "ss", $search_string, $search_string );
$stmt -> execute();
$result = $stmt -> get_result();

$item_count_row = $result -> fetch_assoc();

$total_results = $item_count_row['number_of_items'];

$total_pages = ceil ( $total_results / $max_results_per_page );
$start_from = ( $page - 1 ) * $max_results_per_page;

$query = "
SELECT *
FROM items
WHERE deleted != 'y'
AND ( keywords LIKE CONCAT('%',?,'%') OR title LIKE CONCAT('%',?,'%') )
ORDER BY id DESC LIMIT ?,?";

$stmt = $mysqli -> prepare($query);
$stmt -> bind_param( "ssss", $search_string, $search_string, $start_from, $max_results_per_page );
$stmt -> execute();
$result = $stmt -> get_result();

while ( $item_row = $result -> fetch_assoc() ) {

$item_id = $item_row['id'];
$item_title = $item_row['title'];

echo $item_id;
echo $item_title;

}


if ( $total_results > $max_results_per_page ) {
if ( $page > 1 ) { $prev = $page -1; }
if ( $page == 1 ) { $prev = $total_pages; }
if ( $page < 1 ) { $prev = 1; }
if ( $page < $total_pages ) { $next = $page +1; }
if ( $page == $total_pages ) { $next = 1; }
if ( $page > $total_pages ) {
$next = $total_pages;
$page = 1;
}

echo '
<<< $prev | Page '.$page.' of '.$total_pages.' | $next >>>
';



Comments

There are no comments.


Comment on this Article

Your email address will never be published. Comments are usually approved within an hour or two. (to prevent spam)