Dynamically Generating Page Numbers - php

I currently have an index.php page which serves as an index for a "My Bookmarks" page. The page returns the results of a MySQL Database Query, into a table, which is automatically generated. The code is only supposed to allow five records per page, before generating an additional page (thus inserting page numbers/links at the bottom) - For some reason, my code just stopped working/producing the page numbers.
What is wrong with my code? I can't seem to find the problem and I don't know what to search on the forum; any guidance is much appreciated.
Here is my index.php code:
<?php
session_start();
//check session first
if (!isset($_SESSION['email'])){
echo "You are not logged in!";
exit();
}else{
//include the header
include ("../includes/header.php");
require_once ('../../mysql_connect.php');
echo ("<center>");
echo ("<div class='bookmarkMenu'><h1 style='text-decoration:underline;'>Q & A Database</h2><p>");
echo ("<p><a class='bookmarkAdd' href=add.php>Add Record</a> ");
echo ("<a class='bookmarkSearch' href=searchform.php>Search Records</a></p><hr /></div><br />");
//Set the number of records to display per page
$display = 5;
//Check if the number of required pages has been determined
if(isset($_GET['p'])&&is_numeric($_GET['p'])){//Already been determined
$pages = $_GET['p'];
}else{//Need to determine
//Count the number of records;
$query = "SELECT COUNT(ID) FROM bookmark";
$result = #mysql_query($query);
$row = #mysql_fetch_array($result, MYSQL_NUM);
$records = $row[0]; //get the number of records
//Calculate the number of pages ...
if($records > $display){//More than 1 page is needed
$pages = ceil($records/$display);
}else{
$pages = 1;
}
}// End of p IF.
//Determine where in the database to start returning results ...
if(isset($_GET['s'])&&is_numeric($_GET['s'])){
$start = $_GET['s'];
}else{
$start = 0;
}
//Make the paginated query;
$query = "SELECT * FROM answers LIMIT $start, $display";
$result = #mysql_query ($query);
//Table header:
echo "<table class='bookmarksTable' cellpadding=5 cellspacing=5 border=1><tr>
<th>ID</th><th>Question</th><th>Answer</th><th>Comment</th><th>*</th><th>*</th></tr>";
//Fetch and print all the records...
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "<tr><td class='bookmarkInfo'>".$row['ID']."</td>";
echo "<td class='bookmarkInfo'>".$row['Question']."</td>";
echo "<td class='bookmarkInfo'>".$row['Answer']."</td>";
echo "<td class='bookmarkInfo'>".$row['Comment']."</td>";
echo "<td class='bookmarkInfo'>Delete</td>";
echo "<td class='bookmarkInfo'>Update</td></tr>";
} // End of While statement
echo "</table>";
mysql_free_result ($result); // Free up the resources.
mysql_close(); // Close the database connection.
//Make the links to other pages if necessary.
if($pages>1){
echo '<br/><table><tr>';
//Determine what page the script is on:
$current_page = ($start/$display) + 1;
//If it is not the first page, make a Previous button:
if($current_page != 1){
echo '<td> Previous </td>';
}
//Make all the numbered pages:
for($i = 1; $i <= $pages; $i++){
if($i != $current_page){ // if not the current pages, generates links to that page
echo '<td> ' . $i . ' </td>';
}else{ // if current page, print the page number
echo '<td>'. $i. '</td>';
}
} //End of FOR loop
//If it is not the last page, make a Next button:
if($current_page != $pages){
echo '<td> Next </td>';
}
echo '</tr></table>'; //Close the table.
}//End of pages links
//include the footer
include ("../includes/footer.php");
}
?>
Much thanks,
-Rockmandew

you should be counting from answers table and do page logics based on that then your query on answers table at the bottom would fit

Related

Paginate multiple search query using single file

I have one file example.com/search_category.php. There are different subcategories in database. I don't want to open file for each category, rather I want to paginate using single file. If I open file for each category such as example.com/search_category/subcategory1.php, example.com/search_category/subcategory2.php etc then there is no problem. How is it possible to paginate using single file. I am using the following pagination code. Thanks in advance.
// how many rows to show per page
$rowsPerPage = 5;
// by default we show first page
$page_num = 1;
// if $_GET['page'] defined, use it as page number, $_GET gets the page number out of the url
//set by the $page_pagination below
if(isset($_GET['page'])){$page_num = $_GET['page'];}
//the point to start for the limit query
$offset = ($page_num - 1) * $rowsPerPage;
// Zero is an incorrect page, so switch the zero with 1, mainly because it will cause an error with the SQL
if($page_num == 0) {$page_num = 1;}
// counting the offset
$sql = "SELECT * FROM xyz WHERE subcategory='$subcategory' ORDER BY info_id ASC LIMIT $offset, $rowsPerPage ";
$res = mysql_query($sql) or die(mysql_error());
// how many rows we have in database
$sql2 = "SELECT COUNT(subcategory) AS numrows FROM xyz WHERE subcategory= '$subcategory' ";
$res2 = mysql_query($sql2) or die(mysql_error());
$row2 = mysql_fetch_array($res2);
$numrows = $row2['numrows'];
// print the random numbers
while($row = mysql_fetch_array($res))
{
extract ($row);
//Echo out your table contents here.
echo "<tr class=\"alt\" onmouseover=\"ChangeColor(this, true);\" \n";
echo "style=\"cursor: pointer;\"\n";
echo " onmouseout=\"ChangeColor(this, false);\" \n";
echo " onclick=\"DoNav('http://www.example.com/searched_page.php?info_id={$info_id}');\">\n";
echo "\n";
$info_id = $row['info_id'];
echo "</td>";
echo "<td>". $info_id . "</td>";
echo "<td>". $bname . "</td>";
echo "<td>". $text . "</td>";
echo "</tr>";
}
?>
<?php
// how many pages we have when using paging?
$maxPage = ceil($numrows/$rowsPerPage);
$self = "http://www.example.com/search_category.php";
// creating 'previous' and 'next' link
// plus 'first page' and 'last page' link
// print 'previous' link only if we're not
// on page one
if ( $page_num > 1 ) {
$page = $page_num - 1;
$prev = " [Prev] ";
$first = " [First Page] ";
} else {
$prev = ' [Prev] '; // we're on page one, don't enable 'previous' link
$first = ' [First Page] '; // nor 'first page' link
}
// print 'next' link only if we're not
// on the last page
if ( $page_num < $maxPage ) {
$page = $page_num + 1;
$next = " [Next] ";
$last = " [Last Page] ";
} else {
$next = ' [Next] '; // we're on the last page, don't enable 'next' link
$last = ' [Last Page] '; // nor 'last page' link
}
// print the page navigation link
//echo $first . $prev . " Showing page <strong>$page_num</strong> of <strong>$maxPage</strong> pages " . $next . $last;
?>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="center" class="smaller">
<?php
// print the page navigation link
echo '<br>';
echo $first . $prev . " Page <strong>$page_num</strong> of <strong>$maxPage</strong>" . $next . $last;
?>
</table>

How to set the default view into last page in pagination:PHP

Here is my script which I got from the internet,
<?php
// connect to the database
include('connect-db.php');
// number of results to show per page
$per_page = 5;
// figure out the total pages in the database
if ($result = $mysqli->query("SELECT * FROM players ORDER BY id"))
{
if ($result->num_rows != 0)
{
$total_results = $result->num_rows;
// ceil() returns the next highest integer value by rounding up value if necessary
$total_pages = ceil($total_results / $per_page);
// check if the 'page' variable is set in the URL (ex: view-paginated.php?page=1)
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = $_GET['page'];
// make sure the $show_page value is valid
if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page -1) * $per_page;
$end = $start + $per_page;
}
else
{
// error - show first set of results
$start = 0;
$end = $per_page;
}
}
else
{
// if page isn't set, show first set of results
$start = 0;
$end = $per_page;
}
// display pagination
echo "<p><a href='view.php'>View All</a> | <b>View Page:</b> ";
for ($i = 1; $i <= $total_pages; $i++)
{
if (isset($_GET['page']) && $_GET['page'] == $i)
{
echo $i . " ";
}
else
{
echo "<a href='view-paginated.php?page=$i'>$i</a> ";
}
}
echo "</p>";
// display data in table
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th></th> <th></th></tr>";
// loop through results of database query, displaying them in the table
for ($i = $start; $i < $end; $i++)
{
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) { break; }
// find specific row
$result->data_seek($i);
$row = $result->fetch_row();
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row[0] . '</td>';
echo '<td>' . $row[1] . '</td>';
echo '<td>' . $row[2] . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
}
else
{
echo "No results to display!";
}
}
// error with the query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
?>
This program views the 1st page but I want to set the default view into last page after inserted the last row data into the table "players". I got one something like reverse pagination but I don't know how to set it. I'm not good at php. please help!

Pagination in Php SQLITE

I'm quite new to PHP. I'm playing around with connecting to a sqlite database and I've done that successfully. For some reason my pagination is not working.
The value of $page won't go beyond 2. Can someone help me out, I'm sure its probably a simple mistake. (So currently it does change from the first page to the next.
<?php
try
{
//open the database
$db = new PDO('sqlite:client.db');
//create the database
$db->exec("CREATE TABLE IF NOT EXISTS Client (id INTEGER PRIMARY KEY AUTOINCREMENT, first_name VARCHAR(50), last_name VARCHAR(50), email VARCHAR(50), gender VARCHAR(50))");
$page = 1;
if(!empty($_GET['page'])) {
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
if(false === $page) {
$page = 1;
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//something posted
if (isset($_POST['Previous'])) {
print 'current value of $page = ' . $page;
print "<br>";
if($page <= 0) {
$page = 1;
}else {
$page = $page - 1;
}
} else if(isset($_POST['Next'])) {
print 'current value of $page = ' . $page;
print "<br>";
$page = $page + 1;
}
}
// set the number of items to display per page
$limit = 10;
// build query
$offset = ($page - 1) * $limit;
if($offset <= 0) {
$offset = 0;
}
print '$page = ' . $page;
print "<br>";
print '$offset = ' . $offset;
//now output the data to a simple html table...
print "<table border=1>";
print "<tr><td>Id</td><td>First Name</td><td>Last Name</td><td>Age</td><td>Gender</td></tr>";
$sql = "SELECT * FROM Client LIMIT " . $offset . "," . $limit;
$result = $db->query($sql);
//$rows = count($result);
//print $rows;
//checks if table has data
//$count = $result->fetchColumn();
foreach($result as $row)
{
print "<tr><td>".$row['id']."</td>";
print "<td>".$row['first_name']."</td>";
print "<td>".$row['last_name']."</td>";
print "<td>".$row['email']."</td>";
print "<td>".$row['gender']."</td></tr>";
}
print "</table>";
print "<br>";
//print "<button type=\"button\" name=\"button\"><< Previous </button>";
//print "<button type=\"button\" name=\"button\">Next >></button>";
print "<form class=\"\" action=\"\" method=\"post\">";
print "<button type=\"submit\" name=\"Previous\">Previous</button>";
print "<br><br><button type=\"submit\" name=\"Next\">Next</button>";
print "</form>";
// close the database connection
$db = NULL;
}
catch(PDOException $e)
{
print 'Exception : '.$e->getMessage();
}
?>
All credit goes to Ryan-Vincent for helping me solve this.
Basically, I had everything working, but had the incorrect attribute for the form action.
This is the only thing I changed and it worked fine (this is the opening form tag in html, notice the page url parameter gets its value from the php page variable.
print "<form class=\"\" action=\"?page=$page \" method=\"POST\">";
Hope this helps other php newbies.

Last echo'd HTML source not shown (shown completely red in 'view source')

I was actually working on an answer for someone elses question untill I run into something odd. The question was about writing a pagination system. The user wanted something extra added to his current system. So I've written the following code:
<?php
// Database Settings
$dbhost = 'localhost';
$dbuser = '';
$dbpass = '';
$dbname = '';
// Establish Connection to the Database
$dbh = new PDO('mysql:host='. $dbhost .';dbname='. $dbname, $dbuser, $dbpass, array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
// Selecting the data from table but with limit
$query = 'SELECT * FROM table_name ORDER BY column_name ASC LIMIT :start, :page';
// Prepare query
$pre = $dbh->prepare($query);
// Binding values
$pre->bindParam(':start', $start_from);
$pre->bindParam(':page', $per_page);
// Results per page
$per_page=2;
if (isset($_GET['page'])) {
$page = $_GET['page'];
} else {
$page=1;
}
// Page will start from 0 and Multiple by Per Page
$start_from = ($page-1) * $per_page;
?>
<!-- Start building HTML table -->
<table>
<?php
// Execute query
try {
$pre->execute();
// Fetch all results
$results = $pre->fetchAll(PDO::FETCH_ASSOC);
// Loop through results
foreach($results as $data){
// Display results in HTML table
echo "<tr>";
// Add/Remove your column names here
echo "<td>". $data['column_name'] ."</td>";
echo "<td>". $data['column_name'] ."</td>";
echo "<td>". $data['column_name'] ."</td>";
// Close HTML table row
echo "</tr>";
}
} catch (PDOException $e) {
echo 'MySQL query error: ' . $e->getMessage();
}
?>
<!-- End building HTML table -->
</table>
<div>
<?php
// Now select all data from table
$query = 'SELECT * FROM users';
// Prepare the query
$pre = $dbh->prepare($query);
// Execute the query
try {
$pre->execute();
// Count the results
$total_records = $pre->rowCount();
// Keep a record of total number of rows
$total_rows = $total_records;
// Using ceil function to divide the total records on per page
$total_pages = ceil($total_records / $per_page);
// Going to first page
echo "<center><a href='pagination.php?page=1'>First Page</a> ";
// Showing number of pages in between last page
for ($i=1; $i<=$total_pages; $i++){
echo "<a href='pagination.php?page=". $i ."'>". $i ."</a> ";
}
// Going to last page
echo "Last Page</center> ";
} catch (PDOException $e) {
echo 'MySQL query error: ' . $e->getMessage();
}
// Calculate first and last item on current page
$first = $page * $per_page - $per_page;
$last = $page * $per_page;
// Showing the results
echo "<br />";
echo "Showing ". $first ." to ". $last ." in total record of ". $total_rows;
?>
</div>
The code returns no errors and seems to display the data just fine. However, everything echo'd from line 112 (underneath // Going to last page) won't display on the page. It does display in the HTML source code with the correct values. But it's completely marked red in both Firefox and Chrome.
I've never encountered this before and I'm wandering what's causing this?
This kind of problem generally means that your HTML is not well formed.
Look at that line :
echo "Last Page</center> ";
A simple quote is missing before >Last Page ;)
it should be
echo "<a href='pagination.php?page=". $total_pages ."'>Last Page</a></center> ";

how to show selected user to view mysql data

this code showing all MySQL table data to any users but i want only admin and user to show data of mysql query
i have multiple users
1.admin
2.user123
3.xyz
so i want only admin and user to show MySQL table data how can i do this
example
if admin and user123 open the page then mysql data showing correct if xyz user open the page then it will not showing any data
user login name <?php echo $_SESSION['SESS_FIRST_NAME']; ?>
i want to add this one in to mysql query to showing result only admin and user
$query = "SELECT * FROM `follower` WHERE `followername` LIKE '".$letter."%' ORDER BY `followername` ASC LIMIT $from, $max_results";
complete code
<?php
$max_results = 10;
$from = (($page * $max_results) - $max_results);
if(empty($_POST)) {
$query = "SELECT * FROM `follower` WHERE `followername` LIKE '".$letter."%' ORDER BY `followername` ASC LIMIT $from, $max_results";
}
$result = mysql_query("SET NAMES utf8"); //the main trick
$result = mysql_query($query) or die(mysql_error());
$rows = mysql_num_rows($result);
echo "<table class='gridtable' border='1' cellpadding='0' cellspacing='0'>";
echo "<tr><th>Name</th><th>Company Name</th><th>Mobile No</th></tr>";
if ($rows > 0) {
while($row = mysql_fetch_array($result)) {
echo "<tr><td>";
echo $row['followername'];
echo "</td><td>";
echo $row['companyname'];
echo "</td><td>";
echo $row['mobileno'];
echo "</td><td>";
echo $row['contractdatee'];
echo "</td></tr>";
}
} else {
echo "<tr><td align=\"center\" colspan=\"4\">No results found!</td></tr>";
}
echo "</table>";
// Figure out the total number of results in DB:
$total_results = mysql_result(mysql_query("SELECT COUNT(*) as followername FROM follower ORDER BY followername ASC"),0);
// Figure out the total number of pages. Always round up using ceil()
$total_pages = ceil($total_results / $max_results);
// Build Page Number Hyperlinks
echo "<p class=\"style2\">Pages: ";
// Build Previous Link
if($page > 1){
$prev = ($page - 1);
echo "Previous ";
}
for($i = 1; $i <= $total_pages; $i++){
if(($page) == $i){
echo "$i ";
} else {
echo " ";
}
}
// Build Next Link
if($page < $total_pages){
$next = ($page + 1);
echo "Next";
}
echo "</p>";
mysql_close();
?>

Categories