It is not possible to display page-by-page data that the user will be looking for on the site. When dividing the information page by page, on 1 page it displays the number of results specified for display on each page, and no information is displayed on the other pages. For example, I am looking for information from the data, it finds 9 rows. 2 lines should be displayed on each page + 1 on the last page, since (9-1)/2 = 4. And the information is displayed only on 1 search page and on the rest it is empty.
<?php
$connection = mysqli_connect('localhost','root','root','bd');
$text_search = trim(isset($_POST['text_search']) ? $_POST['text_search'] : '');
$query ="select * FROM `raiting_marka` WHERE marka LIKE '%$text_search%' LIMIT 50;";
if(isset($_POST["text_search"])){
//Обрезаем пробелы с начала и с конца строки
$text_search = trim($_POST["text_search"]);
//Проверяем переменную на пустоту
if(!empty($text_search)){
// Для безопасности, преобразуем специальные символы в HTML-сущности
$text_search = htmlspecialchars($text_search, ENT_QUOTES);
$result = mysqli_query($connection, $query) or die("Помилка " . mysqli_error($connection));
$row_cnt = $result->num_rows;
if ($row_cnt == 1) {
printf("<h2 class='search-h2'> Знайдено (%d запит) </h2><br>", $row_cnt);
}
else if ($row_cnt < 1) {
printf("<h2 class='search-h2'> Знайдено (%d запитів) </h2><br>", $row_cnt);
}
else if ($row_cnt <= 4) {
printf("<h2 class='search-h2'> Знайдено (%d запити) </h2><br>", $row_cnt);
}
else if ($row_cnt > 4) {
printf("<h2 class='search-h2'> Знайдено (%d запитів) </h2><br>", $row_cnt);
}
if($result){ ?>
<?php $results_per_page = 2;
//find the total number of results stored in the database
$number_of_result = mysqli_num_rows($result);
//determine the total number of pages available
$number_of_page = ceil ($number_of_result / $results_per_page);
//determine which page number visitor is currently on
if (!isset ($_GET['page']) ) {
$page = 1;
} else {
$page = $_GET['page'];
}
//determine the sql LIMIT starting number for the results on the displaying page
$page_first_result = ($page-1) * $results_per_page;
//retrieve the selected results from database
$query = "SELECT * FROM `raiting_marka` LIMIT " . $page_first_result . ',' . $results_per_page;
$result = mysqli_query($connection, $query);
foreach ($result as $key => $value): ?>
<div class="well">
<?php echo $value['marka']; ?><br><br> <?php echo $value['raiting'].'<br>'; ?>
</div>
<?php endforeach ?>
<?php //display the link of the pages in URL
for($page = 1; $page<= $number_of_page; $page++) {
echo '' . $page . ' '; } ?>
<?php mysqli_free_result($result); }
mysqli_close($connection);
}
else{
printf("<h2 class='search-h2'> Знайдено (0 запитів) </h2><br>");
}
}
?>
help paginate the data you're looking for
Related
I have a little script that have a Previous & Next button.
My problem is I want to detect & place the ID in those buttons
this is the code from the pagination
<body>
<?php include_once 'data.php'; ?>
<center>
<ul class="pagination">
<?php
if($page_counter == 0){
echo "<li><a href=?start='0' class='active'>0</a></li>";
for($j=1; $j < $paginations; $j++) {
echo "";
}
}else{
echo "<a href=?start=$previous><button>Previous</button></a>";
for($j=0; $j < $paginations; $j++) {
if($j == $page_counter) {
echo " ";
}else{
echo " ";
}
}if($j != $page_counter+1)
echo "<a href=?start=$next><button>Next</button></a>";
}
?>
</ul>
</center>
In this part I have the ID but the problem is I can`t get it with this example to place it into the pagination.
<?php
foreach($result as $row) {
echo '
<div class="card"><button1>
'. $row['notice_id'] .'
<div class="time-left">
<div class="dropdown1">
' ;
}
}
else {
echo '';
}
$conn->close();
?>
</div></div>
This is the code from data.php I think I need to place some code into for detection from the ID
<?php
//include configuration file
require 'configuration.php';
$start = 0; $per_page = 1;
$page_counter = 0;
$next = $page_counter + 1;
$previous = $page_counter - 1;
if(isset($_GET['start'])){
$start = $_GET['start'];
$page_counter = $_GET['start'];
$start = $start * $per_page;
$next = $page_counter + 1;
$previous = $page_counter - 1;
}
// query to get messages from messages table
$q = "SELECT * FROM group_notice LIMIT $start, $per_page";
$query = $db->prepare($q);
$query->execute();
if($query->rowCount() > 0){
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}
// count total number of rows in students table
$count_query = "SELECT * FROM group_notice";
$query = $db->prepare($count_query);
$query->execute();
$count = $query->rowCount();
// calculate the pagination number by dividing total number of rows with per page.
$paginations = ceil($count / $per_page);
?>
You can use some formulas for calculate limit and offset of results.
For example you have 100 records, and you want to paginate it into 10 records per page, and the formula is like below.
// Get Page from Query String
$page = 1;
if(!empty($_GET["page"])){
$page = $_GET["page"];
}
// Get record count
$count_query = "SELECT * FROM group_notice";
$query = $db->prepare($count_query);
$query->execute();
$count = $query->rowCount();
$per_page = 10; // records per page
$pages = ceil($count/$per_page); // get total page
$start = $page * $per_page - $per_page; // get offset
// Do something with your records
$query = db->prepare("SELECT * FROM group_notice LIMIT ?, ?");
$query->bind_param("ii", $start, $per_page); // you should use bind param if you use prepared statement
$query->execute();
if($query->rowCount() > 0){
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}
if($page > 1){
echo 'Prev'; // Print Prev Page
}
for($i = 1; $i <= $pages){
echo ''.$i.''; // Print Page Number
}
if($page < $pages){
echo 'Next'; // Print Next Page
}
Hope it helps.
Looking for some help please. I am using the following code to filter and show results which works fine. My problem is the results aren't passing on to the second page so the page becomes blank no errors. very new to this so all help is welcome.
$num_rec_per_page=2;
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("searchresults") or die("ERROR");
if (!isset($_POST['submit'])) exit();
$vars = array('companyname','location');
$verified = TRUE;
foreach ($vars as $v) {
if (!isset($_POST[$v]) || empty($_POST[$v])) {
$verified = FALSE;
}
}
if (!$verified) {
echo "Sorry no results found, please enter your search";
exit();
}
// isset function is also used in checking for the existence of data in $_POST
if (isset($_POST["companyname"]) && $_POST["companyname"] != '') {
$companyname = mysql_real_escape_string($_POST["companyname"]);
$companyname = " AND (companyname LIKE '%$companyname%')";
}
if (isset($_POST["location"]) && $_POST["location"] != '') {
$location = mysql_real_escape_string($_POST["location"]);
$location = " AND (location LIKE '%$location%')";
}
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $num_rec_per_page;
$sql = "SELECT * FROM reviewsandtips WHERE member_id > 0". $companyname . $location . "LIMIT $start_from, $num_rec_per_page";
$sql_result = mysql_query($sql) or die (mysql_error());
// now echo the code for the table heading
if (mysql_num_rows($sql_result)>0) {
while ($row = mysql_fetch_assoc($sql_result)) {
}
$sql = "SELECT * FROM reviewsandtips WHERE member_id > 0". $companyname . $location;
$sql_result = mysql_query($sql); //run the query
$total_records = mysql_num_rows($sql_result); //count number of records
$total_pages = ceil($total_records / $num_rec_per_page);
echo "<a href='codetest.php?page=1'>".'|<'."</a> "; // Goto 1st page
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='codetest.php?page=".$i."'>".$i."</a> ";
}
echo "<a href='codetest.php?page=$total_pages'>".'>|'."</a> "; // Goto last page
} else {
echo '<tr><td colspan="5">No results found.</td></tr>';
}
I have following code to display only 10 records at one page. When I load the page for the first time, first 10 records are displayed well (see screenshot)
. But when I click on "Next 10 records", the same URL is not loaded with extra GET parameters using $_SERVER['PHP_SELF'].
My address bar shows this instead:
http://localhost/PHP/$_SERVER['PHP_SELF']?page=$page
Here is my complete code;
<?php
$con = #mysqli_connect( "localhost:3306", "root", "P#ssw0rd", "world" ) or die ("Couldn't connect to server");
//get total number of records
$query = "SELECT count(ID) FROM city";
$result = mysqli_query ( $con, $query) or die ("Couldn't execute SELECT query: ". mysqli_error($con));
$rec_count = mysqli_num_rows($result);
$rec_limit = 10; //number of records to display
if( isset($_GET['page']) ){ //when user clicks link
$page = $_POST['page'] + 1; //page count increment by 1
$offset = $rec_limit * $page;
}
else{ //user has not yet clicked any link
$page = 0;
$offset = 0;
}
//xxxxxxxx $rec_count is taken from result set
$left_rec = $rec_count - ($page * $rec_limit); //number of records remaining to display
$display_query = "SELECT * FROM city LIMIT $offset, $rec_limit";
$display_result = mysqli_query ( $con, $display_query) or die ("Couldn't execute SELECT query: ". mysqli_error($con));
echo "<table>";
echo "<th>ID</th> <th>Name</th> <th>Country Code</th> <th>District</th> <th>Population</th>";
while( $row = mysqli_fetch_assoc($display_result) ){
extract($row);
echo "<tr>
<td>$ID</td>
<td>$Name</td>
<td>$CountryCode</td>
<td>$District</td>
<td>$Population</td>
</tr>";
}
echo "</table>";
if( $page == 0 ){ //user has not yet clicked any link
echo ' Next 10 records ';
}
else if( $page>0 ){ //user has clicked at least once on link
$last = $page - 2; //here -2 because, in isset block again increment by 1
echo '<a href='. $_SERVER['PHP_SELF']. '?page=$last> Last 10 records </a>';
echo '<a href='. $_SERVER['PHP_SELF']. '?page=$page> Next 10 records </a>';
}
else if( $left_rec < $rec_limit ){ //when only records less than 10 remains
$last = $page - 2;
echo '<a href='. $_SERVER['PHP_SELF']. '?page=$last> Last 10 records </a>';
}
?>
if( $page == 0 ){ //user has not yet clicked any link
echo ' Next 10 records ';
}
This will fix your single and double quotes and will echo the values instead of the variables. You have to apply the same logic to all the inputs.
You can also do:
if( $page == 0 ){ //user has not yet clicked any link
echo " Next 10 records ';
}
echo ' Next 10 records ';
And similar $last.
so I'm having some issues with a pagination script I have been building The pagination works fine however when i load a new page using the next button, my search term $search_term = "%" . $_POST['searchBar'] . "%"; is lost. is there any way to avoid this? or set the search term as a set value?
the url for the next page is like so - http://examplewebsite.com/user/Courses/SearchResultsPage.php?pn=2
Any help with this would be greatly appreciated.
The rest of the pagination script is below;
<?php
$mysqli = new mysqli('localhost', 'user', 'password','db');
if ($mysqli->connect_errno)
{
die('Database connection failed');
}
//$m->set_charset('utf8');
//here are my main changes
//turn errors on to develop, back off when you go live
error_reporting(E_ALL);
ini_set('display_errors', 1);
$search_term = "%" . $_POST['searchBar'] . "%";
$search_param = $_SESSION['$search_term']=$search_term;
$stmt =$mysqli->prepare("SELECT title, summary, id FROM course WHERE title
LIKE ?");
$stmt->bind_param("s", $search_param); //learn this
$stmt->execute();
$result = $stmt->get_result();
//This gets the number of rows in a query result
$rows = $result->num_rows;
//number of results per page
$rows_per_page = 10;
//shows last page
$last_page = ceil($rows/$rows_per_page);
if($last_page < 1){
$last_page = 1;
}
if(isset($_GET['pn'])){
$page_number = preg_replace('#[^0-9]#', '', $_GET['pn']);
} else {
$page_number = 1;
}
//makes sure page number is between limits of $page_number
if($page_number < 1){
$page_number = 1;
} else if($page_number > $last_page){
$page_number = $last_page;
}
// sets the value of items to view
$limit = 'LIMIT ' .($page_number -1) * $rows_per_page .',' .$rows_per_page;
//displays to the user the total number of results and the page numbers
$total_number_of_results = "Search Results (<b>$rows</b>)";
$page_user_is_on = "Page <b>$page_number</b> of <b>$last_page</b>";
//query again only grabbing the set number of rows depending on page number
$stmt = $mysqli->prepare("SELECT title, summary, id FROM course WHERE title LIKE ? ".$limit);
$stmt->bind_param("s", $search_param);
$stmt->execute();
$result = $stmt->get_result();
$list = '';
while($row = $result->fetch_assoc()){
$title = $row['title'];
$id = $row['id'];
//I'm assuming you want each link to be different here...
$list.='<p>' . $title . '</p>';
}
mysqli_close($mysqli);
//set up pagination
$pagination_controls = '';
if($last_page != 1){
if($page_number > 1){
$previous = $page_number - 1;
$pagination_controls .='previous ';
for($i = $page_number - 4; $i < $page_number; $i++)
{
if($i > 0){
$pagination_controls .= ''.$i.' ';
}
}
}
$pagination_controls.=''.$page_number.' ';
//clickable links to the left
for($i = $page_number+1; $i <= $last_page; $i++)
{
$pagination_controls .= ''.$i.' ';
if($i >= $page_number+4){
break;
}
}
if($page_number != $last_page){
$next = $page_number + 1;
$pagination_controls.=' Next';
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel='stylesheet' href='courses.css'>
</head>
<body>
<div class="header">
<h1>Search Results for - <?= $search_param ?></h1>
</div>
<div>
<h3> <?php echo $page_user_is_on ?> </h3>
<p><?php echo $list; ?></p>
<p><?php /* echo $search_result['summary']; //Where was this coming from? */?> </p>
</div>
<div id="pagination_controls"><?php echo $pagination_controls; ?></div>
</body>
</html>
Every time you click next, the page refreshes and since you dont use
<?php
session_start();
....
Replace these 2 lines
$search_term = "%" . $_POST['searchBar'] . "%";
$search_param = $_SESSION['$search_term']=$search_term;
with:
if(isset( $_POST['searchBar'])){
$search_term = "%" . $_POST['searchBar'] . "%";
$search_param = $_SESSION['search'] = $search_term ;
}
else {
$search_param = $_SESSION['search'];
}
at the top,$_SESSION['$search_term'] is lost
Also add an isset check for your POST
EDIT
I think your problem is that $search_term is set only on load then on the next page it is NULL and session is also set to NULL.
I'm trying to do pagination in PHP, everything seems to be working, except that next and previous links don't work, it's only when I manually insert the page number in the URL that it displays data from the database on the next page.
Here is my code:
This is where I initialised the perpage and page. These are at the beginning of the page.
<?php
$per_page=4;
if (isset($_GET['page'])) {
$page = $_GET['page'];
}
else {
$page=1;
}
$page;
echo $start_from = ($page-1) * $per_page;
//$search = $_POST['search'];
?>
And this is for the next and previous links, those ones that display the results depending on what the user wants to see.
<?php
$query = "select * from services";
$result = mysqli_query($link, $query);
$total_records = mysqli_num_rows($result);
//Using ceil function to divide the total records on per page
$total_pages = ceil($total_records / $per_page);
$prev = $page - 1;
if($page == 1){
echo "<span align='right' class='inactive'>← Prev</span>";
}else{
echo "<a href='livebands.php?page=$prev'><span class='paging-prev'>".'← Prev'."</span></a>";
}
for ($i=1; $i<=2; $i++) {
for ($i=1; $i<=$page; $i++) {
echo "<a href='livebands.php?page=$i'><span class='paging'>" .$i. "</span></a>";
}
}
$page++;
if ($page>$total_pages){
echo "<span align='right' class='inactive'>→ Next</span>";
}else{
echo "<a href='livebands.php?page=$page&per_page=$per_page'><span align='right' class='paging-next'>".'Next →'."</span></a>";
}
?>
If I use you code and hardcode the $total_records variable to 5 for example, the links seem to work.
// $query = "select * from services";
// $result = mysqli_query($link, $query);
// $total_records = mysqli_num_rows($result);
$total_records = 5;
Are you sure that your $total_records is more than 4?