Pagination in Php SQLITE - php

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.

Related

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!

PHP pagination isn't working and I'm not sure why

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.

PHP only display last id number in last row

I'm trying to display 6 items in one page with 3 items in each row. And when the user clicks on the image link it will redirect to another page and display the id. However when the user clicks on the image it does redirect to another page but it shows the id of the last product in the last row of the page, and this is not correct. I'm not sure where I made the mistake. I hope you can look at my code and give me a hint where the mistake lies.
<?PHP
session_start();
function connect()
{
$servername = xxxxxxxx;
$username = xxxxxxxx;
$password = xxxxxxxx;
$dbname = xxxxxxxx;
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
echo 'connection is invalid';
} else {
mysqli_select_db($conn, "mytest");
}
return $conn;
}
function getData()
{
$conn = connect();
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
$startrow = 0;
} else {
$startrow = (int) $_GET['startrow'];
}
$sql = "SELECT * FROM tbl_products LIMIT $startrow, 6";
$getdata = mysqli_query($conn, $sql) or die(mysqli_error());
$cell_img = mysqli_num_rows($getdata);
$i = 0;
$per_row = 3;
echo "<table id='productTumb'><tr id='proRow'>";
$data = '';
while ($row = mysqli_fetch_assoc($getdata)) {
//echo "<a href='ProDet.html'></a>";
echo "<td><a href='test.php'><img style='vertical-align: bottom;' width='218px' height='332px' src='" . $row['products_image'] . "'/ ></a></td>";
$data .= "<td style='background-color:#FF0004'>" . $row['product_name'] . "</td>";
$product_id = $row['products_id'];
$_SESSION['id'] = $product_id;
if (++$i % $per_row == 0 && $i > 0 && $i <= $cell_img) {
echo "</tr><tr>$data</tr><tr>";
$data = '';
}
}
for ($x = 0; $x < $per_row - $i % $per_row; $x++) {
echo "<td></td>";
}
echo "</tr>";
echo "</table>";
echo 'Next >>>';
$prev = $startrow - 5;
if ($prev >= 0)
echo ' <<<< Previous';
}
?>
This line of code $_SESSION['id'] = $product_id; will set last product id to SESSION.(overwrites previous ids)
Try to add product id to the anchor href tag
while ($row = mysqli_fetch_assoc($getdata)) {
echo "<td><a href='test.php?id=".$row['products_id']."'><img style='vertical-align: bottom;' width='218px' height='332px' src='" . $row['products_image'] . "'/ ></a></td>";
......
}
In test.php file get id by below code
if(isset($_GET)){
$pid = $_GET['id'];
echo $pid;
}
hope this will helps you.

"Next" button doesn't refresh page with next 25 results

I have the code below and am trying to get the next 25 results from my sql table to appear on page. However, whenever I click the next button, no information is displayed. I have my offset = ($page - 1) * $items_per_page......I'm struggling to figure this out as it seems so simple compared the other code I've written, but is proving to be very elusive to me....any assistance would be greatly appreciated. My primary issue is that the next link does not provide the next 25 results and I'm unable to determine why and how to correct.
echo "<h3 style='text-align:center;'>Welcome to the Exchange Portal, " . $row['name'] . "! </h3>";
$items_per_page = 25;
$sql_count = "SELECT pin, title, title2, email, phone FROM crown_acura";
$result_cnt = mysqli_query($conn, $sql_count);
if(false === $result_cnt) {
throw new Exception('Query failed with: ' . mysqli_error());
} else {
$row_count = mysqli_num_rows($result_cnt);
// free the result set as you don't need it anymore
//mysqli_free_result($result_cnt);
}
echo $row_count;
echo " ";
if (!isset($_GET['Page'])) {
$Page = 1;
} else {
$Page = $_GET['Page'];
}
echo $page;
echo " ";
$page_count = 0;
if (0 === $row_count) {
// maybe show some error since there is nothing in your table
} else {
// determine page_count
$page_count = (int)ceil($row_count / $items_per_page);
// double check that request page is in range
if($page > $page_count) {
// error to user, maybe set page to 1
$page = 1;
}
}
echo " ";
echo $page_count;
echo " ";
echo $items_per_page;
$offset = ($page-1)*$items_per_page;
//echo $paging_info;
//echo " ";
echo "<br />";
//Query for displaying results
$list_sql = "SELECT pin, title, title2, email, phone FROM crown_acura LIMIT $offset, $items_per_page";
$result_query = $conn->query($list_sql);
//Table for displaying query results
echo "<table class='verify'>";
echo "<tr >";
echo "<td><h3>Name</h3></td><td> </td><td><h3>E-mail</h3></td><td><h3>Phone</h3></td>";
echo "</tr>";
for($i = 1; $i<= $page_count; $i++) {
if ($result_query->num_rows > 0) {
// output data of each row
while($row3 = mysqli_fetch_array($result_query)) {
echo "<tr>";
echo "<td class='dltd2 dlcl'>" . $row3["title"] . "</td><td>" . $row3["title2"] . "</td><td><a href='mailto:" . $row3['email'] . "'>" . $row3["email"] . "</a> </td><td>" . $row3["phone"] . " </td>";
echo "</tr>";
}
} else {
echo "0 results";
}
}
echo "<tr></tr>";
$next_page = $page + 1;
$last_page = $page - 1;
if($paging_info['curr_page'] <= 1) {
echo "<tr>";
echo "<td></td><td colspan='2'><a class='loadlink' href='" . $_PHP_SELF . "'>Next 25</a></td><td></td>";
echo "</tr>";
} elseif ($paging_info['curr_page'] < $page_count) {
echo "<tr>";
echo "<td></td><td><a href='" . $_PHP_SELF . "?page=" . $last_page . "'>Prev 25</a></td><td><a href='" . $_PHP_SELF . "?page=" . $next_page . "'>Next 25</a></td><td></td>";
echo "</tr>";
} elseif ($paging_info['curr_page'] === $page_count) {
echo "<tr>";
echo "<td></td><td colspan='2'><a href='" . $_PHP_SELF . "?page=" . $last_page . "'>Prev 25</a></td><td></td>";
echo "</tr>";
}
echo "</table>";
}
}
}
Have you tried to run the rendered SQL.
Output to browser:
"SELECT pin, title, title2, email, phone FROM crown_acura LIMIT $offset, $items_per_page"
try this... and change $page for different values (2,3,...,etc)
<?php
$items_per_page = 25;
$sql_count = "SELECT pin, title, title2, email, phone FROM crown_acura";
$result_cnt = mysqli_query($conn, $sql_count);
if (false === $result_cnt) {
throw new Exception('Query failed with: ' . mysqli_error());
} else {
$row_count = mysqli_num_rows($result_cnt);
// free the result set as you don't need it anymore
//mysqli_free_result($result_cnt);
}
echo $row_count;
echo " ";
if (!isset($_GET['Page'])) {
$Page = 1;
} else {
$Page = $_GET['Page'];
}
echo $page;
echo " ";
$page_count = 0;
if (0 === $row_count) {
// maybe show some error since there is nothing in your table
} else {
// determine page_count
$page_count = (int)ceil($row_count / $items_per_page);
// double check that request page is in range
if ($page > $page_count) {
// error to user, maybe set page to 1
$page = 1;
}
}
echo " ";
echo $page_count;
echo " ";
echo $items_per_page;
$offset = ($page - 1) * $items_per_page;
//echo $paging_info;
//echo " ";
echo "<br />";
//Query for displaying results
$list_sql = "SELECT pin, title, title2, email, phone FROM crown_acura LIMIT $offset, $items_per_page";
$result_query = $conn->query($list_sql);
echo ("RESULTS: ".$result_query->num_rows());
?>

Dynamically Generating Page Numbers

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

Categories