I have been working at this all day and still at 8pm have had no luck. I was wondering if you guys can give me some advice on fixing it. I am building an Upload - gif sharing system for University.
Here is my code anyway -
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
mysql_connect("localhost","root","root") or die("Top Query");
mysql_select_db("UPLOAD") or die(mysql_error());
$count_query = mysql_query("SELECT NULL FROM details");
$count = mysql_num_rows($count_query);
//pagination
if(isset($_GET['page'])){
$page = preg_replace("#[^0-9]#","",$_GET['page']);
}else{
$page= 1;
}
$perPage = 5;
$lastPage = ceil($count / $perPage);
if($page < 1){
$page = 1;
}else if($page > $lastPage){
$page = $lastPage;
}
$limit = "LIMIT " .($page -1) * $perPage . ", $perPage";
//Query and gifs
$query = mysql_query("SELECT * FROM details ORDER BY date_added DESC") or die("2nd Query");
//Puts it into an array
$pagination="";
if($lastPage != 1){
if($page != $lastPage){
$next = $page + 1;
$pagination.='More';
}
if($page != 1){
$prev = $page - 1;
$pagination.='Back';
}
}
?>
And then the output in the html -
<?php
while($info = mysql_fetch_array($query)){
$shortlink = "".$info['photo']." " ;
//Outputs the image and other data
echo "<article class='upload-post'>" . "<div class='crop'>";
echo "<a href=uploads/".$info['photo'].">";
echo "<img class='scale-with-grid' src=uploads/".$info['photo'] .">"."</a>";
echo "</div>";
echo "".$info['name'] . "<br/>";
echo "Reaction ".$info['reaction'] ."<br/>";
echo "In " .$info['category'] ." <br/>";
echo "On " .$info['date_added'] ." <br/>";
echo "Link: $shortlink";
echo "</article>";
}
?>
<?php echo $pagination;?>
I can toggle between pages but its not limiting the number of posts displayed on the page. Id really appreciate the help as the deadline isn't too far away.
Thanks a bunch in advance!
You never append $limit to your query.
Try the follwing as a replacement...
...
//Query and gifs
$query = mysql_query("SELECT * FROM details ORDER BY date_added DESC ".$limit) or die("2nd Query");
//Puts it into an array
...
Related
Can anyone point me out why my pagination is not working, What I am doing wrong here ? Working on it for a long time. my url generates like : http://localhost/medapp/admin/medorder.php?page=%209.
<?php
//pagination
$perpage = 3;
if (isset($_GET["page"])) {
$page = $_GET["page"];
}
else {
$page=1;
}
$start_from = ($page-1)*$perpage;
//pagination
$medorder = "SELECT * FROM `medorder` WHERE status='1' order by ID desc";
$result = $db->select($medorder);
if($result){
$i=0;
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>".$i++."</td>";
echo "<td>".$row["uid"]."</td>";
echo "<td>".$row["fullname"]."</td>";
echo "</tr>";
}
// pagination
$query = "select * from medorder";
$result = $db->select($query);
$total_rows = mysqli_num_rows($result);
$total_pages = ceil($total_rows/$perpage);
echo "<span class='pagination'><a href='medorder.php?page=1'>".'First Page'."</a>";
for ($i=1; $i <= $total_pages; $i++) {
echo "<a href='medorder.php?page=".$i."'>".$i."</a>"; }
echo "<a href='medorder.php?page=$total_pages'>".'Last Page'."</a></span>";
//pagination
}
?>
Change your query like this by using LIMIT and OFFSET
$medorder = "SELECT * FROM `medorder` WHERE status='1' order by ID desc LIMIT $start_from,$perpage"; //
in this following line, you have a space before the $i variable:
echo "<a href='medorder.php?page= ".$i."'>".$i."</a>";
should be
echo "<a href='medorder.php?page=".$i."'>".$i."</a>";
I feel like I ask a lot of questions.
Anyways, I'm writing pagination for some database entries, and it looks sound to me but it's only displaying the first 10 posts and nothing else when I click the links.
The whole shebang is right here:
<?php
$post_limit = 10;
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("failed to connect: " . $conn->connect_error);
}
$sql = "SELECT count(id) FROM $tablename";
$result = mysqli_query($conn, $sql);
if (!$result) {
echo "you fucked up";
} else {
echo $row["id"];
}
$row = mysqli_fetch_array($result, MYSQL_NUM);
$post_count = $row[0];
if(isset($_GET['page'])) {
$page = $_GET['page'] + 1;
$offset = $post_limit * $page;
} else {
$page = 0;
$offset = 0;
}
$post_left = $post_count - ($page * $post_limit);
$sql = "SELECT id, upvotes, downvotes, name, title, message, date, time FROM posts ORDER BY date DESC, time DESC LIMIT $offset, $post_limit";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<br><div id='messageBar'>";
echo " ❖ </b>";
echo "Posted by <b>";
echo htmlspecialchars($row["name"]);
echo "</b> on ";
echo $row["date"];
echo " at ";
echo $row["time"];
if (!empty($row['title'])) {
echo " - <b>";
echo htmlspecialchars($row["title"]);
echo "</b>";
}
echo "<span style='float: right'>#";
echo $row["id"];
echo "</span>";
echo "</div><div id='messageContent'>";
echo htmlspecialchars($row["message"]);
echo "<br><br><span id='commentLink'><a class='commentLink' href='thread.php?id=$row[id]'>view thread </a></span>";
echo "<br></div><br><hr>";
}
} else {
echo "<br>";
echo "<center><i>it's dusty in here</i></center>";
echo "<br>";
}
if ($page > 0) {
$last = $page - 2;
echo "<a href='$_PHP_SELF?page = $last'>previous page</a> | ";
echo "<a href='$_PHP_SELF?page = $page'>next page</a>";
} else if ($page == 0) {
echo "<a href='$_PHP_SELF?page = $page'>next page</a>";
} else if ($post_left < $post_limit) {
$last = $page - 2;
echo "<a href='$_PHP_SELF?page = $last'>previous page</a>";
}
$conn->close();
?>
The link for the next page appears at the bottom, but clicking it takes you to the page you're already on with the same 10 most recent posts.
I am trying to learn PHP as I go, so I appreciate any help. Thank you!
Instead of using $_GET please use $_SESSION to manage a counter.
Every time you go in this page you increment the counter.
So, you have to do this on the top of the page:
if(isset($_SESSION['counter'])) {
$page = $_SESSION['counter'] + 1;
$offset = $post_limit * $page;
} else {
$page = 0;
$offset = 0;
$_SESSION['counter']=0;
}
Try this.
By the way there is Datatables which do what you're looking for.
P.S. If you don't start sessions in some other points in your code, please put session_start(); in the first page (e.g., login.php) otherwise put on this page.
Fixed. Problem was here:
if ($page > 0) {
$last = $page - 2;
echo "<a href='$_PHP_SELF?page = $last'>previous page</a> | ";
echo "<a href='$_PHP_SELF?page = $page'>next page</a>";
} else if ($page == 0) {
echo "<a href='$_PHP_SELF?page = $page'>next page</a>";
} else if ($post_left < $post_limit) {
$last = $page - 2;
echo "<a href='$_PHP_SELF?page = $last'>previous page</a>";
}
The URL I was linking to wasn't supposed to have spaces around the = sign. It's still buggy, but it works.
I have few records in MySQL DB table.
Displayed those records with pagination PREV and NEXT.
Page ids are displaying in url bar.
http://localhost/pagination.php?page=5
I don't want them while pagination clicking.
How can i do this?
Here is my code.
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("moodle");
$per_page = 10;
$pages_query = mysql_query("SELECT COUNT('id') FROM question");
$pages = ceil(mysql_result($pages_query, 0) / $per_page);
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $per_page;
$query = mysql_query("SELECT * FROM question LIMIT $start, $per_page");
while($query_row = mysql_fetch_assoc($query)){
echo $query_row['id']."<br />";
}
$prev = $page - 1;
$next = $page + 1;
echo "<a href='pagination.php?page=$prev'>Prev</a> ";
if($pages >= 1){
for($x=1; $x<=$pages; $x++){
echo ''.$x.' ';
}
}
echo "<a href='pagination.php?page=$next'>Next</a> ";
?>
Use id in session and don't display it in url . other method is to use Ajax call in pagination on click of previous or next button . i think these are two simple solutions for you that you can easily manage .
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>
I would like to paginate my multi termed sql query in paginated results, page 1 works fine but page 2..previous or next do not pass the variable:
<?php
include "db.inc.php";
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * 15;
$term1 = $_REQUEST['term1'];
$term2 = $_REQUEST['term2'];
$term3 = $_REQUEST['term3'];
$term4 = $_REQUEST['term4'];
$sql ="SELECT * FROM cdrequests WHERE pname LIKE '%$term1%' AND date LIKE '%$term2%' AND date LIKE '%$term3%' AND dept LIKE '%$term4%' LIMIT $start_from, 15";
$rs_result = mysql_query ($sql);
$num_rows = mysql_num_rows($rs_result);
$query = mysql_query("SELECT * FROM cdrequests WHERE pname LIKE '%$term1%' AND date LIKE '%$term2%' AND date LIKE '%$term3%' AND dept LIKE '%$term4%'");
$number=mysql_num_rows($query);
print "<font size=\"5\" color=white><b>CD Requests</b></font> </P>";
print "<table class=\"table1\" STYLE=\"word-wrap:break-word;\" width=1100 border=\"1\" bordercolor=\"#000000\" bgcolor=\"E6E6E6\" style=\"border-collapse: collapse\" cellpadding=\"2\" cellspacing=\"1\"> .............
?>
<?php
$term1 = $_REQUEST['term1'];
$term2 = $_REQUEST['term2'];
$term3 = $_REQUEST['term3'];
$term4 = $_REQUEST['term4'];
$sql = "SELECT COUNT(id) FROM cdrequests WHERE pname LIKE '%$term1%' AND date LIKE '%$term2%' AND date LIKE '%$term3%' AND dept LIKE '%$term4%'";
$rs_result = mysql_query($sql);
$row = mysql_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / 15);
/****** build the pagination links ******/
// range of num links to show
$range = 3;
// if not on page 1, don't show back links
if ($page > 1) {
// show << link to go back to page 1
echo " <a href='search2.php?page=1'><b>First</b></a> ";
// get previous page num
$prev = $page - 1;
// show < link to go back to 1 page
echo " <a href='search2.php?page=$prev'><b>«</b></a> ";
} // end if
// loop to show links to range of pages around current page
for ($x = ($page - $range); $x < (($page + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $total_pages)) {
// if we're on current page...
if ($x == $page) {
// 'highlight' it but don't make a link
echo " <font size='5' color=yellow><b> $x </b></font> ";
// if not current page...
} else {
// make it a link
echo " <a href='search2.php?page=$x'>$x</a> ";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($page != $total_pages) {
// get next page
$next = $page + 1;
// echo forward link for next page
echo " <a href='search2.php?page=$next'><b>»</b></a> ";
// echo forward link for lastpage
echo " <a href='search2.php?page=$total_pages'><b>Last</b></a> ";
} // end if
/****** end build pagination links ******/
echo " <font size='4' color=white>Total Records</font> <font size='5' color=yellow><b>$number</b></font>";
echo '</table>';
?>
not sure what I need to put in the echo " <a href='search2.php?page=$next'><b>»</b></a> "; in order to call the terms
thanks
Does this not work?
...
$start_from=$page*15
$query = mysql_query("SELECT * FROM cdrequests WHERE ...");
$all_rows = mysql_num_rows($query);
$totalPages = ceil($all_rows/15)-1; #How many pages?
$sql = $query . " LIMIT $start_from,15";
print "<font size=\"5\" color=white><b>CD Requests</b></font> </P>";
print "<table class=\"table1\..."
$terms= '&term1='.$term1 . '&term2='.$term2 . '&term3='.$term3 . '&term4='.$term4;
if($totalPages>1){
#Paging Starts Now
?>
<div align="center">
<? if ($page > 1) { ?>
Previous
First
<? } ?>
Page <? echo $page; ?> of <? echo $totalPages+1; ?>
<? if ($page < $totalPages) { ?>
Next
Last
</div>
<? } }?>
Make it much easier on yourself. Build the table once.
Apply jQuery Datatables to it
$('#table_id).datatables();
Paging done. It's really that easy! All it requires is jQuery and the DataTables plugin, plus a few lines of CSS. As a bonus, it will filter, sort, limit, and more with just additional line of code per feature required. Plus, it can be styled with Themeroller, making a better looking table than most developers can pull off.