Page 1 of 1
php pagination
Posted: Sun Jan 10, 2010 4:11 am
by DonthDragon
Hi.
I am pretty new to php and am struggling to get a php pagination going.
I found a script to help me out, but I cant understand how I can call items from a database and the put it into an array.
Below is a snippet of the code
Code: Select all
//create an array of names in alphabetic order. A database call could have retrieved these items
$names = array("Andrew", "Bernard", "Castello", "Dennis", "Ernie", "Frank", "Greg", "Henry", "Isac", "Jax", "Kester", "Leonard", "Matthew", "Nigel", "Oscar");
Can someone help with this issue?
Cheers
Donovan
Re: php pagination
Posted: Sun Jan 10, 2010 12:19 pm
by divito
There's a few ways you could do it, but it's easier if one knows what needs to happen after that. For instance, do you really need the array? Pulling from the database can put the names automatically in order.
Re: php pagination
Posted: Sun Jan 10, 2010 3:00 pm
by satikas
Change the SELECT lines according to your needs. For example ...ORDER BY name DESC/ASC.
From:
http://php.about.com/od/phpwithmysql/ss ... nation.htm
Note that this script has a bug in it.
"$pagenum" has no value, to assign it do: $pagenum = $_GET["pagenum"]; OR if (!(isset($_GET["pagenum"]))){
around line 10
Code: Select all
<?php
// Connects to your Database
mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error());
mysql_select_db("address") 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 topsites") or die(mysql_error());
$rows = mysql_num_rows($data);
//This is the number of results displayed per page
$page_rows = 4;
//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 topsites $max") or die(mysql_error());
//This is where you display your query results
while($info = mysql_fetch_array( $data_p ))
{
Print $info['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> ";
}
?>
Re: php pagination
Posted: Mon Jan 11, 2010 5:18 am
by DonthDragon
Thank you for getting back to me. I apologise if I sound uneducated on this issue (because I probably am), Im actually doing a property website and need results to show from a search query.
Below is my exact code :
Code: Select all
<div id="house">
<h2>Search results</h2>
<?php
// Create short variable names
$area = $_POST['area'];
$price_from = str_replace(" ","",$_POST['price_from']);
$price_to = str_replace(" ","",$_POST['price_to']);
@ $db = new mysqli('localhost', '*****', '*****', '*****');
if (mysqli_connect_errno()) {
echo 'Error : Could not connect to database. Please try again later.';
exit;
}
$query = "select * from property_profile where property_profile.area='".mysql_real_escape_string($area)."' and (property_profile.price between '".mysql_real_escape_string($price_from)."' and '".mysql_real_escape_string($price_to)."')" or die(mysql_error());
$result = $db->query($query);
$num_results = $result->num_rows;
echo "<h2>Results matching your query : ".$num_results."</h2>";
for ($i=0; $i<=$num_results; $i++) {
$row_getProp = $result->fetch_assoc();
?>
<div id="house">
<div class="profile">
<div id="contphp">
<div class="prop">
<div class="price">
<h3><span>R<?php echo number_format($row_getProp['price']); ?></span> <?php echo ($row_getProp['target_area']); ?></h3>
<p>Reference number : <?php echo $row_getProp['reference']; ?></p>
</div>
<div class="img_gal">
<?php
$parola = '';
$my_array = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v");
for ($i=0; $i<=10; $i++)
{
$random = array_rand($my_array);
//this generates the random number from the array
// echo "<br> count $i <br> $random call";
// echo the count number and the random number called from array_rand
if ($check[$random]<>0) {
$i--;
// echo "ed already try again";
// if check array isnt = 0 then the random number has been already called re random by taking 1 from $i to ensure correct number of results
} else {
$check[$random]=1;
// set check to 1 so it knows the array number has been used
$parola .= $my_array[$random];}
//here we will display the exact charachter from the array
}
// printing result
?>
<script type="text/javascript">
$(window).bind("load", function() {
$("div#mygalone<?php echo $parola; ?>").slideView()
});
</script>
<?php
$imagelist = $row_getProp[image];
$images = explode(',',$imagelist);
?>
<div id="mygalone<?php echo $parola; ?>" class="svw">
<ul>
<?php
for ($i=0;$i < count($images) ; $i++)
{
?>
<li><img alt="<?php echo $images[$i] ; ?>" src="upload/<?php echo $images[$i] ; ?>" width="230" height="180"/></li>
<?php
}
?>
</ul>
</div>
<script type="text/javascript">
$(window).bind("load", function() {
$("div#<?php echo $parola ; ?>").slideView({
easeFunc: "easeInOutBack",
easeTime: 2200
});
});
</script>
</div>
<div class="details">
<table>
<tr class="one">
<th>Bedrooms</th>
<td><?php echo $row_getProp['bedrooms']; ?></td>
<th>Bathrooms</th>
<td><?php echo $row_getProp['bathrooms']; ?></td>
</tr>
<tr>
<th>Garages</th>
<td><?php echo $row_getProp['garages']; ?></td>
<th>Pool</th>
<td><?php echo $row_getProp['pool']; ?></td>
</tr>
<tr class="one">
<th>Fencing</th>
<td><?php echo $row_getProp['fencing']; ?></td>
<th>Security</th>
<td><?php
if (!(strcmp($row_getProp['security'],"security"))) {
echo "yes";
} else {
echo "No";
}
?> </td>
</tr>
<tr>
<th>
Outbuildings
</th>
<td>
<?php echo $row_getProp['fencing']; ?>
</td>
<th>
Land use
</th>
<td>
<?php echo $row_getProp['land_use']; ?>
</td>
</tr>
<tr>
<th>
Size of farm
</th>
<td>
<?php echo $row_getProp['size']; ?>
</td>
<th>
Water
</th>
<td>
<?php echo $row_getProp['water']; ?>
</td>
</tr>
</table>
</div>
<div class="desc">
<h3>Description :</h3>
<p><?php echo $row_getProp['description']; ?></p>
</div>
</div>
</div>
</div>
</div>
<?php
}
$result->free();
$db->close();
?>
</div>
</div>
</div>
</body>
</html>
<?php
mysql_free_result($getProp);
?>
Based on that, how would I implement the pagination into my page.
Thanks
Donovan
Re: php pagination
Posted: Tue Jan 12, 2010 11:46 pm
by ramblin54321
Put this on line 20 it is for two displays per page so change all of the 2s to how many results you want per page.
of course you will change 'entries' to your database table name and 'created' to your desired sort variable
// Display the page links
$page = 1;
$prev_page = $page - 1;
$next_page = $page +1;
$num_pages = CEIL($num_rows / 2);
$page_start = (2 * $page) - 2;
//put the limit in the query to get output for each page
$query="SELECT * FROM entries ORDER BY created DESC LIMIT $page_start, 2";
$result = mysql_query($query) or die("Couldn't execute query");
The following is what I have instead of your line 24 which I think yours is o.k. the way it is.
while ( $row = mysql_fetch_array($result) ) {
Then before your output, you need to query the database a second time with the page limit in place:
$query="SELECT * FROM entries ORDER BY created DESC LIMIT $page_start, 2";
$result = mysql_query($query) or die("Couldn't execute query");
// Start a table for the output.
Then you will need a second page like your first only without lines 1-9 that you call pagename, the following code will send the rest of the results to the other pages:
echo "<div class = pages> <br><br>";
// Set up the page links and pass any needed variables to the next page by including them in the href after the page variable.
if (!$prev_page < "1") {
echo"<a href='pagename.php?page=$prev_page&num_pages=$num_pages'><font color='#400000'>< Previous page.</font></a>";
}
if ($page != $num_pages) {
echo "<a href='pagename.php?page=$next_page&num_pages=$num_pages'><font color='#400000'> Next page.></font></a></CENTER>";
}
All of the above pagination code goes on the pagename.php page also except that you must add this before prev page and instead of page=1:
if ( $_GET["page"] == NULL )
$page = 0;
else
$page = $_GET["page"];
$start = (2 * $page) - 2;
$num_pages = $_GET["num_pages"];
// Display the page links:
if(!$page) {
$page = 1;
}
Re: php pagination
Posted: Wed Jan 13, 2010 3:55 am
by DonthDragon
ok. I have tried to implement the code, but still cant seem to get it right.
Please can you have a look at my updated code.
Code: Select all
<?php require_once('Connections/propProfile.php'); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Search results</title>
</head>
<body>
<div id="wrapper">
<p class="accessaid"><a href="#consume" title="Skip past the navagation, to the content">Skip to page content</a></p>
<div id="consume">
<div id="house">
<h2>Search results</h2>
<?php
// Create short variable names
$area = $_POST['area'];
$price_from = str_replace(" ","",$_POST['price_from']);
$price_to = str_replace(" ","",$_POST['price_to']);
@ $db = new mysqli('localhost', 'root', '****', '*****');
if (mysqli_connect_errno()) {
echo 'Error : Could not connect to database. Please try again later.';
exit;
}
// Display the page links
$page = 1;
$prev_page = $page - 1;
$next_page = $page +1;
$num_pages = CEIL($num_rows / 2);
$page_start = (2 * $page) - 2;
//put the limit in the query to get output for each page
$query="select * from property_profile where area='".mysql_real_escape_string($area)."' and (price between '".mysql_real_escape_string($price_from)."' and '".mysql_real_escape_string($price_to)."') $page_start, 2";
$result = mysql_query($query) or die("Couldn't execute query");
while ( $row_getProp = mysql_fetch_array($result) ) {
$query="select * from property_profile where area='".mysql_real_escape_string($area)."' and (price between '".mysql_real_escape_string($price_from)."' and '".mysql_real_escape_string($price_to)."') $page_start, 2";
$result = mysql_query($query) or die("Couldn't execute query");
// Start a table for the output.
?>
<div id="house">
<div class="profile">
<div id="contphp">
<div class="prop">
<div class="price">
<h3><span>R<?php echo number_format($row_getProp['price']); ?></span> <?php echo ($row_getProp['target_area']); ?></h3>
<p>Reference number : <?php echo $row_getProp['reference']; ?></p>
</div>
<div class="img_gal">
<?php
$parola = '';
$my_array = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v");
for ($i=0; $i<=10; $i++)
{
$random = array_rand($my_array);
//this generates the random number from the array
// echo "<br> count $i <br> $random call";
// echo the count number and the random number called from array_rand
if ($check[$random]<>0) {
$i--;
// echo "ed already try again";
// if check array isnt = 0 then the random number has been already called re random by taking 1 from $i to ensure correct number of results
} else {
$check[$random]=1;
// set check to 1 so it knows the array number has been used
$parola .= $my_array[$random];}
//here we will display the exact charachter from the array
}
// printing result
?>
<script type="text/javascript">
$(window).bind("load", function() {
$("div#mygalone<?php echo $parola; ?>").slideView()
});
</script>
<?php
$imagelist = $row_getProp[image];
$images = explode(',',$imagelist);
?>
<div id="mygalone<?php echo $parola; ?>" class="svw">
<ul>
<?php
for ($i=0;$i < count($images) ; $i++)
{
?>
<li><img alt="<?php echo $images[$i] ; ?>" src="upload/<?php echo $images[$i] ; ?>" width="230" height="180"/></li>
<?php
}
?>
</ul>
</div>
<script type="text/javascript">
$(window).bind("load", function() {
$("div#<?php echo $parola ; ?>").slideView({
easeFunc: "easeInOutBack",
easeTime: 2200
});
});
</script>
</div>
<div class="details">
<table>
<tr class="one">
<th>Bedrooms</th>
<td><?php echo $row_getProp['bedrooms']; ?></td>
<th>Bathrooms</th>
<td><?php echo $row_getProp['bathrooms']; ?></td>
</tr>
<tr>
<th>Garages</th>
<td><?php echo $row_getProp['garages']; ?></td>
<th>Pool</th>
<td><?php echo $row_getProp['pool']; ?></td>
</tr>
<tr class="one">
<th>Fencing</th>
<td><?php echo $row_getProp['fencing']; ?></td>
<th>Security</th>
<td><?php
if (!(strcmp($row_getProp['security'],"security"))) {
echo "yes";
} else {
echo "No";
}
?> </td>
</tr>
<tr>
<th>
Outbuildings
</th>
<td>
<?php echo $row_getProp['fencing']; ?>
</td>
<th>
Land use
</th>
<td>
<?php echo $row_getProp['land_use']; ?>
</td>
</tr>
<tr>
<th>
Size of farm
</th>
<td>
<?php echo $row_getProp['size']; ?>
</td>
<th>
Water
</th>
<td>
<?php echo $row_getProp['water']; ?>
</td>
</tr>
</table>
</div>
<div class="desc">
<h3>Description :</h3>
<p><?php echo $row_getProp['description']; ?></p>
</div>
</div>
</div>
</div>
</div>
<?php
echo "<div class = pages> <br><br>";
// Set up the page links and pass any needed variables to the next page by including them in the href after the page variable.
if (!$prev_page < "1") {
echo"<a href='pagename.php?page=$prev_page&num_pages=$num_pages'><font color='#400000'>< Previous page.</font></a>";
}
if ($page != $num_pages) {
echo "<a href='pagename.php?page=$next_page&num_pages=$num_pages'><font color='#400000'> Next page.></font></a></CENTER>";
}
}
$result->free();
$db->close();
?>
</div>
</div>
</div>
</body>
</html>
<?php
mysql_free_result($getProp);
?>
I know im probably being a pain in the butt, cause its probably so easy for an experienced coder. For that I am sorry.
Cheers
Donovan
Re: php pagination
Posted: Sun Jan 17, 2010 5:30 am
by ramblin54321
Sorry I told you one thing wrong in my previous post. The first time you do your query which is on line 35, you don't put the limit in. So take off the page start 2 from that statement. On line 36 change $result to $numresults. Then put this right below line 36 $num_rows = mysql_num_rows($numresults);
Put your while statement in with your php on line 49. and put your query statements that have the limit currently on line 40 and 41 move them to right before your while statement within the same php tag. Finally put the part about the page link variables (currently 28-33) somewhere after the $num_rows that I told you to put on line 37.
To sum up:
1st $query = your normal query.
2nd $numresults = mysql_query($query);
3rd $num_rows = mysql_num_rows($numresults);
4th $page = 1;
$prev_page = $page - 1;
$next_page = $page +1;
$num_pages = CEIL($num_rows / 2);
$page_start = (2 * $page) - 2;
5th $query="SELECT your normal query LIMIT $page_start, 2";
6th $result = mysql_query($query) or die("Couldn't execute query");
7th while ( $row = mysql_fetch_array($result) ) {
8th print stuff
9th the page links that you have on 127-133
Re: php pagination
Posted: Tue Feb 09, 2010 1:56 am
by DonthDragon
Hi. Just want to say that I have finally sorted the problem out (along with some new grey hairs).
Thanks to everyone who helped me. Really appreciate it.
cheers. Have a brilliant week.
Donovan