dropdown menu with pagination - php

I have a dropdown filter which displays results directly from my database. I also have pagination which controls my pages. I am trying to get my dropdown to store results which at the moment i have had no success. my filter has 3 things: all, snake, reptile. When I click the option it displays the name e.g. snake. But when I press page 2 or 3 the result disappears and the dropdown goes back to all rather then stay on the selected option.
Okay update: when i click page 1,2 or 3 then the filter it shows correct results is there a way i can skip having to keep clicking the filter to show results on next page
So far I have tried: I have tried to create a session and also kept session start at the beginning which didn't help. I have also changed post to get when requesting the results. I have results set to two per page but it only displays two results when I click the option. As soon as I press 1,2,3, it displays no results. I have also tried using JavaScript to create a function getselected items and added a one click get selected item but still no results. What i want to happen: I click snake (which has 4 names in the database) I want it to display two names on page 1, and 2. Here is my base code:
$s = "SELECT DISTINCT name from users";
$result = $con->query($s);
echo "<form id='id' method='get' name='myform'>";
echo "<select name='fetch' class='filter' action='pagprofiletest.php'>";
echo "<option value='All'>All</option>";
if($result = mysqli_query($con, $s)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
$output = "<option value='".$row['name']."'"; //keeps select option on dropdown the same upon page refresh
if($_GET['fetch'] == $row['name']){
$output .= " selected='selected'";
}
$output .= ">".$row['name']."</option>";
echo $output;
}
echo "</select>";
echo "<input id='submit' name='submit' type='submit' value='submit' onclick='reload()'></input>";
echo "</form>";
}
}
?>
<?php
// $sql = "SELECT count(id) FROM users WHERE approved='1'";
$sql = "SELECT count(*) FROM users";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_row($query);
//here we have the total row count
$rows = $row[0];
//this is the number of results we want displayed per page
$page_rows = 2;
//this tells us the page number of last page
$last = ceil($rows/$page_rows);
//this makes sure last cannot be less then 1
if($last < 1){
$last =11;
}
//establish $pagenum variable
$pagenum = 1;
//get pagenum from url vars if it is present, else it is =1
if(isset($_GET['pn'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
// this makes sure page number isnt below 1, or more then $last page
if($pagenum < 1){
$pagenum = 1;
} else if($pagenum > $last){
$pagenum = $last;
}
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
$sql = "SELECT name FROM users WHERE approved='1' $limit";
$query = mysqli_query($con, $sql);
$textline1 = "users (<b>$rows</b>)";
$textline2 = "Page <b>$pagenum</b> of <br>$last</b>";
$paginationCtrls = '';
if($last != 1){
if($pagenum > 1){
$previous = $pagenum -1;
$paginationCtrls .= 'previous ';
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i > 0){
$paginationCtrls .=''.$i.' ';
}
}
}
$paginationCtrls .=''.$pagenum.' ';
for($i = $pagenum+1; $i <=$last; $i++){
$paginationCtrls .= ''.$i.' ';
if($i >= $pagenum+4){
break;
}
}
if($pagenum != $last){
$next = $pagenum + 1;
// $paginationCtrls .= ' Next ';
$paginationCtrls .= ' Next ';
}
}
if($pagenum != $last){
$lastpage= $last;
$paginationCtrls .= ' Last ';
}
if($pagenum == $last){
$first =l;
$paginationCtrls .= ' First ';
}

Related

Pagination. Why only one page is showing?

I have been trying to get pagination to work and I have to a certain extent but it only shows one page of results.
I have 18 listings in my database and have it set to show 6 per page.
Can anyone see what the problem is?
<?php include('includes/configsql.php');
//include header template
include('layout/header.php');
//include navbar template
include('layout/navbar.php');
?>
<?php
$con = mysqli_connect($db_hostname,$db_username,$db_password,$db_database);
$sql = "SELECT COUNT(id) FROM basic WHERE status='active'";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_row($query);
$rows = $row[0];
$rows = mysqli_num_rows($query);
$page_rows = 6;
$last = ceil($rows/$page_rows);
if($last < 1){
$last = 1;
}
$pagenum = 1;
if(isset($_GET['pn'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
if ($pagenum < 1) {
$pagenum = 1;
} else if ($pagenum > $last) {
$pagenum = $last;
}
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
$sql = "SELECT id, name, address, telephone, email, category FROM basic WHERE status='active' ORDER BY name ASC $limit";
$query = mysqli_query($con, $sql);
$textline1 = "Basic Listing (<b>$rows</b>)";
$textline2 = "Page <b>$pagenum</b> of <b>$last</b>";
$paginationCtrls = '';
if($last != 1){
if ($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCtrls .= 'Previous ';
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i > 0){
$paginationCtrls .= ''.$i.' ';
}
}
}
$paginationCtrls .= ''.$pagenum.' ';
for($i = $pagenum+1; $i <= $last; $i++){
$paginationCtrls .= ''.$i.' ';
if($i >= $pagenum+4){
break;
}
}
if ($pagenum != $last) {
$next = $pagenum + 1;
$paginationCtrls .= ' Next ';
}
}
$list = '';
while($row = mysqli_fetch_array($query)){
$id = $row["id"];
$name = $row["name"];
$category = $row["category"];
$list .= '<p>'.$name.' | '.$category.' - Click the link to view this business</p>';
}
mysqli_close($con);
?>
<div id="wrapper">
<div id="bizlist">
<div id="pagination">
<h2><?php echo $textline1; ?></h2>
<p><?php echo $textline2; ?></p>
<p><?php echo $list; ?></p>
<div id="pagination_controls"><?php echo $paginationCtrls; ?></div>
</div>
</div>
<?php
//include footer template
include('layout/footer.php');
?>
I think you have to remove the line:
$rows = mysqli_num_rows($query);
It is in beginning of the script.
Another way is if you modify the first line like this:
$sql = "SELECT * FROM basic WHERE status='active'";
And remove the next 3 rows
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_row($query);
$rows = $row[0];
You have to choice one of above, but not both :)

PHP MySQL Paging

I tried so many different solutions. Im new to php since 1 week, used ASP 12 years ago so I hope I can get some help.
Everything down here works fine. But there are around 1000 rows in the db and I need to split them up in pages.
<?php
$con = mysqli_connect("localhost","test","test","test")or die('could not connect to database');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo "<table border='0'>
<tr>
<th>Img:</th>
<th>Text:</th>
</tr>";
$result = mysqli_query($con,"SELECT Jokes.ID, Categories.CategoryName, Jokes.CategoryID, Jokes.JokeText FROM Jokes LEFT JOIN Categories ON Jokes.CategoryID = Categories.ID ORDER BY Jokes.JokeText");
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td align='center'><img src='webimg/" . $row['CategoryName'] . ".png' height='35' width='35'></td>";
echo "<td align='left' width='80%'>" . $row['JokeText'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Kind Regards.
You can use MySQL LIMIT for that.
I've used to do it like this:
Get the total number of rows you're paging and have a parameter like in the URL, i.e. "/p/5" or ?page=5 (I will use this for reference, easier to write code and for you to understand) for page no. 5, also do a failsafe, like this:
Say you have 10 records per page:
$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
$records_per_page = 10;
And, in your SQL you will have something like this
$start = ($page-1) * $records_per_page;
$result = mysql_query("select * from table limit {$start}, {$records_per_page}");
Kind of crude, but you should get the point and be on the right path.
For building your pagination links... that's totally up to you. You should get the total amount of rows with a "select count (PRIMARY_KEY) from table" query prior, so you can calculate the max number of pages.
What you're searching for is the LIMIT of mysql.
The usage is very simple.
For example:
"SELECT * FROM tablename LIMIT 3"
This will give you the first three results.
In your case, you need an offset, depends on the current page:
"SELECT * FROM tablename LIMIT offset,results"
The offset can be calculated, depends on how many results you want each page.
"SELECT * FROM tablename LIMIT 20,10"
This will display 10 results, start at result 20. This could be for the 3. site if you want 10 results each site.
<?php
$per_page = 10; //no. of results to display in one page
$pages_query = mysql_query("SELECT COUNT('id') FROM JOKES");//Or whatever field. this is just to check the number of results.
$pages = ceil(mysql_result($pages_query, 0) / $per_page);//to get the total no. of pages that will be there. For example if u have 60 results than no. og pages will be 60/10=6
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;// if the page variable in your url is set that means that u have clicked a page number. So it will be taking that page number and displaying those results
$start = ($page - 1) * $per_page;//to get the starting result of that page. If you are in say 6th page, then the starting element would be 6-1*10=50. This makes sure that the results in the previous pages are not displayed
$query = mysql_query("SELECT * FROM JOKES LIMIT $start, $per_page");//set the limit of results that page
while($query_row = mysql_fetch_assoc($query)){
echo " ur table names ";
}
$prev = $page - 1;//to set the prev page variable
$next = $page + 1;//to set the next page variable
if(!($page<=1)){
echo "<a href='Yourpagename.php?page=$prev'>Prev</a> ";
}//does not displays the prev variable if you are already one first page
if($pages>=1 && $page<=$pages){
for($x=1;$x<=$pages;$x++){
echo ($x == $page) ? '<strong>'.$x.'</strong> ' : ''.$x.' ';
}//display all the pages. Display the current page as bold
}
if(!($page>=$pages)){
echo "<a href='Your page name.php?page=$next'>Next</a>";
}//do not display next vvariable if your are in the last page
?>
Thx for all the answers. I came over this tutorial and it worked: http://www.developphp.com/view.php?tid=1349
<?php
include_once("mysqli_connection.php");
$sql = "SELECT COUNT(id) FROM testimonials WHERE approved='1'";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$rows = $row[0];
$page_rows = 10;
$last = ceil($rows/$page_rows);
if($last < 1){
$last = 1;
}
$pagenum = 1;
if(isset($_GET['pn'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
if ($pagenum < 1) {
$pagenum = 1;
} else if ($pagenum > $last) {
$pagenum = $last;
}
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
$sql = "SELECT id, firstname, lastname, datemade FROM testimonials WHERE approved='1' ORDER BY id DESC $limit";
$query = mysqli_query($db_conx, $sql);
$textline1 = "Testimonials (<b>$rows</b>)";
$textline2 = "Page <b>$pagenum</b> of <b>$last</b>";
$paginationCtrls = '';
if($last != 1){
if ($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCtrls .= 'Previous ';
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i > 0){
$paginationCtrls .= ''.$i.' ';
}
}
}
$paginationCtrls .= ''.$pagenum.' ';
for($i = $pagenum+1; $i <= $last; $i++){
$paginationCtrls .= ''.$i.' ';
if($i >= $pagenum+4){
break;
}
}
if ($pagenum != $last) {
$next = $pagenum + 1;
$paginationCtrls .= ' Next ';
}
}
$list = '';
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$firstname = $row["firstname"];
$lastname = $row["lastname"];
$datemade = $row["datemade"];
$datemade = strftime("%b %d, %Y", strtotime($datemade));
$list .= '<p>'.$firstname.' '.$lastname.' Testimonial - Click the link to view this testimonial<br>Written '.$datemade.'</p>';
}
mysqli_close($db_conx);
?>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body{ font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;}
div#pagination_controls{font-size:21px;}
div#pagination_controls > a{ color:#06F; }
div#pagination_controls > a:visited{ color:#06F; }
</style>
</head>
<body>
<div>
<h2><?php echo $textline1; ?> Paged</h2>
<p><?php echo $textline2; ?></p>
<p><?php echo $list; ?></p>
<div id="pagination_controls"><?php echo $paginationCtrls; ?></div>
</div>
</body>
</html>

Lossing session data

I want to perform some data filtering from database. After filtering, session variable is lost and I'm getting this error:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in ..\test.php on line 34.
Can someone help?
FORM:
<form action= "test.php" method='get'>
<select name="Type">
<option value="winter" name="winter">winter</option>
</select>
<input type='submit' value = 'filter'>
</form>
CODE:
<?php
session_start();
$_SESSION['winter'] = $_GET['Type'];
$type = $_SESSION['winter'] ;
include "mysqlConnect.php";
//check for a page number. If not, set it to page 1
if (!(isset($_GET['pagenum']))){
$pagenum = 1;
}else{
$pagenum = $_GET['pagenum'];
}
//query for record count to setup pagination
$data = mysql_query("SELECT * FROM tblPhotos WHERE Type='$type' ");
$rows = mysql_num_rows($data);
//number of photos per page
$page_rows = 16;
//get the last page number
$last = ceil($rows/$page_rows);
//make sure the page number isn't below one, or more than last page num
if ($pagenum < 1){
$pagenum = 1;
}elseif ($pagenum > $last){
$pagenum = $last;
}
//Set the range to display in query
$max = 'limit ' .($pagenum - 1) * $page_rows .',' .$page_rows;
//get all of the photos
$dynamicList = "";
$sql = mysql_query("SELECT * FROM tblPhotos WHERE Type='$type' $max ");
//check for photos
$photoCount = mysql_num_rows($sql); //LINE 34
echo $photoCount;
if ($photoCount > 0){
while($row = mysql_fetch_array($sql)){
$photoID = $row["PhotoID"];
$photoName = $row["photoName"];
$category = $row["category"];
$dynamicList .= '
<div class="thumb">
<img class="clip" src="galleryPhotos/' . $photoID . '.jpg" alt="' . $photoName . '" width="175" border="0" />
</div>
';
}
}else{
$dynamicList = "There are no photos at this time!";
}
mysql_close();
echo '<p style="text-align:center; font-weight:bold;">Page ' . $pagenum . ' of ' . $last . '</p>';
if ($pagenum == 1){
echo '<div class="pagination" align="center"><ul>';
}else{
echo '<div class="pagination" align="center"><ul><li>« first</li>';
$previous = $pagenum-1;
}
//check if number of pages is higher than 1
if($last != 1){
//Loop from 1 to last page to create page number links
for($i = 1; $i <= $last; $i++){
echo '<li>' . $i . '</li>';
}
}
if ($pagenum == $last){
echo '</div>';
}else{
$next = $pagenum+1;
echo '<li>last »</li></ul></div>';
}
echo $dynamicList;
?>
Your Code: mysql_query("SELECT * FROM tblPhotos WHERE Type='$type' $max ");
Read the error message, it is telling you something is wrong with the query. Having looked at the query. I am inclined to agree.

PHP Pagination issue mysql and php showing same data on all pages

I am having issues with some pagination with data i get from a MySQL database in PHP.
My code is below. Basically what happens is it creates the right amount of pages however each page shows the same data and doesn't even show only 5 rows per page.
I'm really stuck. This is my first time trying pagination. Any help would be greatly appreciated.
$pagenum = $_GET['pagenum'];
if (!(isset($pagenum)))
{
$pagenum = 1;
} else
{
$pagenum = $_GET['pagenum'];
}
//Count the number of results.
$data = mysql_query("SELECT * FROM `articles` WHERE `content` = '' AND `requestedby` != '$id'") or die(mysql_error());
$rows = mysql_num_rows($data);
//Set the number of results to be displayed per page.
$page_rows = 5;
//This tells us the page number of our last page
$last = ceil($rows/$page_rows);
//this makes sure the page number isn't below one, or more than our maximum pages
if ($pagenum < 1)
{
$pagenum = 1;
} elseif ($pagenum > $last)
{
$pagenum = $last;
}
//This sets the range to display in our query
$max = 'LIMIT ' . ($pagenum - 1) * $page_rows .',' .$page_rows;
//This is the query again, the same one... the only difference is we add $max into it.
$data_p = mysql_query("SELECT * FROM `articles` WHERE `content` = '' AND `requestedby` != '$id' '$max'") or die(mysql_error());
//Work out writers earnings based on prices.
//100 Words - $1.25
//300 Words - $2.50
//500 Words - $4.00
//700 Words - $5.50
//1000 Words - $8.00
$_100earnings = "0.65";
$_300earnings = "1.25";
$_500earnings = "2.50";
$_700earnings = "3.00";
$_1000earnings = "5.00";
?>
<!-- main -->
<div id="main">
<center><h2>Write Articles</h2></center>
<br />Available Projects:
<table border="1">
<tr>
<td>Title:</td>
<td>Length:</td>
<td>Writers Earnings:</td>
</tr>
<?php
//This is where you display your query results
while($info = mysql_fetch_array($data_p))
{
echo "<tr>";
echo "<td>" . $info['keywords'] . "</td>";
echo "<td>" . $info['length'] . "</td>";
switch ($info['length'])
{
case 100:
$writersearnings = $_100earnings;
break;
case 300:
$writersearnings = $_300earnings;
break;
case 500:
$writersearnings = $_500earnings;
break;
case 700:
$writersearnings = $_700earnings;
break;
case 1000:
$writersearnings = $_1000earnings;
break;
}
echo "<td>$" . $writersearnings . "</td>";
//echo $info['Name'];
echo "</tr>";
}
?>
</table>
<br /><br />
<?php
// This shows the user what page they are on, and the total number of pages
echo " --Page $pagenum of $last-- <p>";
// First we check if we are on page one. If we are then we don't need a link to the previous page or the first page so we do nothing. If we aren't then we generate links to the first page, and to the previous page.
if ($pagenum == 1)
{
} else
{
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=1'> <<-First</a> ";
echo " ";
$previous = $pagenum - 1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$previous'> <-Previous</a> ";
}
//just a spacer
echo " ---- ";
//This does the same as above, only checking if we are on the last page, and then generating the Next and Last links
if ($pagenum == $last)
{
} else
{
$next = $pagenum + 1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$next'>Next -></a> ";
echo " ";
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$last'>Last ->></a> ";
}
use this code, remove ' around $max in query, when you add ' around $max the query becomes select.... from.... where..... 'LIMIT.....' and it fails the query.
$data_p = mysql_query("SELECT * FROM `articles` WHERE `content` = '' AND `requestedby` != '$id' $max") or die(mysql_error());
You need to specify LIMIT in your query LIMIT offset,count
$data_p = mysql_query("SELECT * FROMarticlesWHEREcontent= '' ANDrequestedby!= '$id' '$max'") or die(mysql_error());
Remove the ' quotes from '$max'
$data_p = mysql_query("SELECT * FROM articles WHERE content= '' AND requestedby!= '".$id."' ".$max) or die(mysql_error());

PHP MySql Pagination?

Pagination really confuses me. My code works but it only shows the first page. The next page doesn't work. I just want to show 3 records per page.
Do you have to have another query to show the results of the second page?
<?php
// Connects to your Database
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("db_pet") or die(mysql_error());
//This checks to see if there is a page number. If not, it will set it to page 1
if (!(isset($pagenum)))
{
$pagenum = 1;
}
//Here we count the number of results
//Edit $data to be your query
$data = mysql_query("SELECT * FROM tb_pet") or die(mysql_error());
$rows = mysql_num_rows($data);
//This is the number of results displayed per page
$page_rows = 3;
//This tells us the page number of our last page
$last = ceil($rows/$page_rows);
//this makes sure the page number isn't below one, or more than our maximum pages
if ($pagenum < 1)
{
$pagenum = 1;
}
elseif ($pagenum > $last)
{
$pagenum = $last;
}
//This sets the range to display in our query
$max = 'limit ' .($pagenum - 1) * $page_rows .',' .$page_rows;
//This is your query again, the same one... the only difference is we add $max into it
$data_p = mysql_query("SELECT * FROM tb_pet $max") or die(mysql_error());
//This is where you display your query results
while($info = mysql_fetch_array($data_p))
{
Print $info['pet_name'];
echo "<br>";
}
echo "<p>";
// This shows the user what page they are on, and the total number of pages
echo " --Page $pagenum of $last-- <p>";
// First we check if we are on page one. If we are then we don't need a link to the previous page or the first page so we do nothing. If we aren't then we generate links to the first page, and to the previous page.
if ($pagenum == 1)
{
}
else
{
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=1'> <<-First</a> ";
echo " ";
$previous = $pagenum-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$previous'> <-Previous</a> ";
}
//just a spacer
echo " ---- ";
//This does the same as above, only checking if we are on the last page, and then generating the Next and Last links
if ($pagenum == $last)
{
}
else {
$next = $pagenum+1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$next'>Next -></a> ";
echo " ";
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$last'>Last ->></a> ";
}
?>
if (!(isset($pagenum))) {
$pagenum = 1;
}
you have not set $pagenum any where on this line instead it should be
if (!(isset($_GET['pagenum']))) {
$pagenum = 1;
}else{
$pagenum = $_GET['pagenum'];
}
it is just fix for your code, you need to improve the way you write code and try using PDO instead mysql functions

Categories