PHP/MySQLi Page Numbers and Final query issues - php

I am trying to create a page number function that displays 9 results per page from my forum_replies.sql table. My PHP code so far will only display page 1, page 2. Page 1 has 9 query's but page two has none... but there's 22 rows of data that should be fetched, so at least 2 pages should show!
Here's my code!
if(isset($_GET["p"]) && is_numeric($_GET["p"]) && $_GET["p"] > 1) {
$currentPage = $_GET["p"];
$limiter = $currentPage * 9;
} else {
$currentPage = 1;
$limiter = 0;
}
$finalQuery = "SELECT * FROM forum_replies WHERE thread_id = '1' ORDER BY id ASC LIMIT " . $limiter . ",9";
Figured out that the isset at the top.. $limiter works like this
0,9 = page 1.. correct
18,9 = page 3.. how do I get page 2 (9,9) and so on.. cause it's completely skipping 9,9!

How about calling echo $db->error; after each query? You can also echo the querys and try them in phpMyAdmin to find out what's wrong. I can't spot a mistake in the finalQuery, at least not syntax-wise.

Related

Pagination, wrong amount of results on first page

I'm making news website, and I have mysql db with field "time" like 1533074400
Everything is ok if I just print results from query, but if I want to print only news older than today, I get in result only 2 instead of 5 news on first page. Remaining 3 are on the second page.
The problem is with query, if I receive let's say I have in my database 10 results and only 7 of them are past news, so when I filter them descending by
if ($today > news_date)
I get 2 news on first page (the remaining 3 are invisible future news, blocked by code above) and the rest 5 news on second page. So my question is, what to do to get it properly: 5 news on first page and remaining 2 on second page?
$results_per_page = 5;
if (!isset($_GET['page'])) {
$page = 1;}
else {
$page = $_GET['page'];
}
$this_page_first_result = ($page-1)*$results_per_page;
$sql='SELECT * FROM news ORDER BY time DESC LIMIT ' . $this_page_first_result . ',' . $results_per_page;
$result = mysqli_query($con, $sql);
$number_of_results = mysqli_num_rows($result);
$today = strtotime("now");
while($row = mysqli_fetch_array($result))
{
$news_date = $row[1];
if ($today > $news_date) {
echo HTML;
}
}
$number_of_pages = ceil($number_of_results/$results_per_page);
for ($page=1;$page<=$number_of_pages;$page++) {
echo '' . $page . ' ';
}
Try this:
$sql='SELECT * FROM news WHERE time < '.time().' ORDER BY time DESC LIMIT ' . $this_page_first_result . ',' . $results_per_page;
//Note: time() is an equivalent to strtotime("now")
If you're doing pagination in MySQL you should also do your filtering inside MySQL.
[Edit: Additional explanation] If you paginate in MySQL and then filter in PHP you'll have weird instances like this crop up because MySQL doesn't know where you're intending to actually start from. In this particular example if you have a lot of future-dated items you could actually end up with several blank pages of results pages before you start to see entries.
[Edit edit:] Also, if you do this, you'll no longer need the if check in your PHP loop as MySQL will have already done that.

Link to another page in php pagination?

I have a code with query for in php paging
$page = (isset($_GET['page'])) ? $_GET['page'] : 1;
$startPoint = $page - 1;
$sql="SELECT * FROM ` admin_crmf_poc_event_history`
where $condition
order by event_date asc
LIMIT $startPoint,30";
$result = mysql_query($sql);
and for creating link to next page, i use
Prev
Next
but I give link index.php which shows the whole values from the start. dont know how to give link of next page so the rest of values are shown. Please help??
try it like this
$page = (isset($_GET['page']) && (int)$_GET['page']>0) ? (int)$_GET['page'] : 1);
$startPoint = ($page*30) - 30;
$sql="SELECT * FROM ` admin_crmf_poc_event_history`
where $condition
order by event_date asc
LIMIT $startPoint,30";
$result = mysql_query($sql);
<?php if($page>1){?>Prev<?php } ?>
Next
so what I did is first I added (int) before your $_GET['page'] to cast the $_GET value to int, second thing is I multiplied $page by how many rows per page you want then subtracted rows per page so, if you are at page 1 your start point will be 1*30-30=0 at page 2 it will be 2*30-30=30 etc... Then all you have to do with page links is subtract 1 for previous page and add 1 for next page.

Php pagination from Mysql Select * Where; If click on next page number, then displays all rows from Mysql

In input field user enters condition - what data to get from mysql. For example, user wants to get mysql rows where month is October (or 10).
Here I get user input $date_month = $_POST['date_month'];
Then mysql statement and code for pagination
try {
$sql = $db->prepare("SELECT * FROM 2_1_journal WHERE RecordMonth = ? ");
$sql->execute(array($date_month));
foreach ($sql as $i => $row) {
}
$number_of_fetched_rows = $i;
$number_of_results_per_page = 100;
$total_pages = ceil($number_of_fetched_rows / $number_of_results_per_page);
if (isset($_GET['page']) && is_numeric($_GET['page'])) {
$show_page = $_GET['page'];
if ($show_page > 0 && $show_page <= $total_pages) {
$start = ($show_page -1) * $number_of_results_per_page;
$end = $start + $number_of_results_per_page;
}
else {
$start = 0;
$end = $number_of_results_per_page;
}
}
else {
$start = 0;
$end = $number_of_results_per_page;
}
for ($page_i = 1; $page_i <= $total_pages; $page_i++) {
echo "<a href='__filter_mysql_data.php?page=$page_i'>| $page_i |</a> ";
}
}
So, user enters month (10), script displays all rows where month is 10; displays page No 1. But if user click on other page number, script displays all data from mysql (all months, not only 10)
What I see - when click on other page number, page reloads, that means that values of php variables "dissapears". As understand after page reload $date_month value is not set (has lost/"dissapears") ? How to keep the value? Or may be some better solution for pagination?
Update.
Behavior is following:
1) in input field set month 10 (October);
2) click on button and get displayed data from mysql where month is 10 (October); so far is ok
3) click on page number 2 and get displayed all data from mysql (all months, not only 10 (October))
Tried to use LIMIT however it does not help.
Possibly problem is related with this code
for ($page_i = 1; $page_i <= $total_pages; $page_i++) {
echo "<a href='__filter_mysql_data.php?page=$page_i'>| $page_i |</a> ";
}
When click on $page_i for not understandable (for me) reasons get displayed all (not filtered) data from mysql. If I use LIMIT also get displayed not filtered results from mysql....
Use LIMIT in your query, have a look at the following example , you can try something like :
SELECT
*
FROM
2_1_journal
WHERE
RecordMonth = ?
LIMIT [start_row],[number_of_rows_per_page]
So for example lets say you have 2 pages with 10 rows per page then the LIMIT for the 2 queries (one per page) will be:
1) LIMIT 0,10
2) LIMIT 10,10
You should change your query like this:
SELECT * FROM 2_1_journal WHERE RecordMonth = ? LIMIT = $number_of_results_per_page OFFSET ($page_number*$number_of_results_per_page);
Here you need to calculate the page number also and you should use the limit and offset concept of mysql.

How to hide the next button when no pages to dispaly

Can someone help me please? I am sure it is easy for you guys. I am battling to find a solution on how to hide the next link when there are no pages to display my code is as follows:
if (!isset($_GET['page']) or !is_numeric($_GET['page'])) {
$page = 0;
} else {
$page = (int)$_GET['page'];
}
$pages_query=mysql_query ("SELECT COUNT * FROM hardware");
$result = mysql_query("SELECT * FROM hardware LIMIT $page, 3");
echo 'Next<p>';
$prev = $page - 3;
//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0) {
echo 'Previous';
}
You can use mysql_num_rows($result) to get the number of records in hardware:
$result = mysql_query("SELECT * FROM hardware LIMIT $page, 3");
$record_count = mysql_num_rows($result);
if ($record_count > 1)
echo 'Next';
in your if statement check if the $page is greater than 0 then according to the outcome of the value of $page write your code. you can use another if statement in the first if statement and make it detect the situation and decide what to do. The other thing is if the user clicked next then the user is on the second page so your previous should appear if $prev is higher than 1 it should make it
something along the lines of:
$itemsPerPage = 3;
$sql = "SELECT * FROM hardware";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$pageCount = $count/$itemsPerPage;
if($pageCount > $page) { //Are there more pages worth of items stored, than we're currently looking at?
echo 'next';
}
You want to be using OFFSET in your SQL syntax, as well as LIMIT.
LIMIT limits the number of rows returned.
OFFSET tells it to start a number of rows into the result set.
You need to limit to the number of items you want on a page. and offset by that number*page.
Hopes this helps.

php pagination for search result failing to display

i've just been learning pagination. i'm having trouble getting it to work for search results. it displays the first page correctly with the right number of links but clicking on any of the links (even on the page 1) goes to a blank page.
can somebody please tell me what i'm doing wrong:
The following code is for when the search button is clicked.
<?php
include('includes/connect-db.php');
include('includes/functions.php');
if (isset($_GET['searchbtn'])){
$product=$_GET['products'];
$status=$_GET['ticket_status'];
$order_by=$_GET['order_by'];
$ticket_type=$_GET['ticket_type'];
#check if product has been selected
if ($_GET['products'] == 'select'){
echo '<font class="error">&nbsp Please select a product to search.</font>';
}else{
if ($status == 'All' AND $order_by == 'All' AND $ticket_type == 'All' ){
$page_query="SELECT * FROM tickets WHERE product='$product' ORDER BY created DESC";
}elseif ($ticket_type == 'BOX'){
$page_query="SELECT * FROM tickets WHERE product='$product' AND status='$status' AND pbi <> '-' ORDER BY '$order_by' ";
}elseif ($ticket_type == 'PVR'){
$page_query="SELECT * FROM tickets WHERE product='$product' AND status='$status' AND inc <> '-' ORDER BY '$order_by' ";
}else{
$page_query="SELECT * FROM tickets WHERE product='$product' AND status='$status' ORDER BY created DESC";
}
}#end of else
$results_per_page=3;
$result_set=pagination($results_per_page,$page_query);
$query=$result_set['query'];
$pages=$result_set['pages'];
#SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset. A resource on success or False on Error
if (!empty($query)){
$result = mysqli_query($db,$query) or die( "My query ($query) generated an error: ".mysql_error());
$num_results = mysqli_num_rows($result);
if ($num_results > 0){
displayTicket($result);
if ($pages > 1){
echo '</br>';
for($i=1;$i<=$pages;$i++){
echo ' '.$i.' ';
}
}
}else{
echo "&nbsp No Records found.";
}
}#query string is not empty
}
?>
i have put the pagination code in a separate function:
function pagination($per_page, $pages_query){
include('includes/connect-db.php');
$pagination[]=array();
#total result count
$total_result=mysqli_query($db,$pages_query);
#ceil takes a decimal number and gives the nearest whole number
$total=mysqli_num_rows($total_result);
$pages = ceil($total / $per_page);
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $per_page;
$query = " LIMIT $start,$per_page";
$query = $pages_query.$query;
$pagination['query'] = $query;
$pagination['pages'] = $pages;
return $pagination;
}
Note: the pagination linking to other pages only fails when i attempt it with the search feature. i have tried it on a page that lists information in a table and the links work fine.
It looks to me like the problem is the information in the link: localhost/test/searchProductForm.php?page=1 tells searchProductForm which page to display, but it doesn't tell it what the search information was. Without that, your search page has no idea what to display. Try changing the pagination link to include all the information that was in the original search link (i.e., your products, ticket_status, order_by, and ticket_type parameters).
I know this is an old thread, but for anyone not able to solve a similar problem with the code used above, it could be to do with the lack of session_start() at the beginning of the document.
I say this because although the code is trying to obtain the session variables passed by the ?page= &products= etc to $_GET statements but they are not being retrieved into the variables from the URL but you need to place the session_start() at the begging of your PHP document to pass the information from the URL to the strings.

Categories