Table pagination not going to a different page when selected - php

I added pagination to a table a I created a while back and I have not ever been able to get it to work correctly since.
The table limit works, but that's it. If I select "First, Last or the page number" it just reloads the page, but the new page does not display.
If I set the page limit to a low number like 5 and select 'Last Page', when the page loads it shows =1 like it doesn't know there are other pages.
<?php
$con = mysqli_connect("localhost","root","","bfb");
$per_page=20;
if(isset($_POST["page"])) {
$page = $_POST["page"];
}
else {
$page = 1;
}
//Page will start from 0 and multiply per page
$start_from = ($page-1)*$per_page;
//Selecting the data from the table but with limit
$query = "SELECT * FROM orders LIMIT $start_from, $per_page";
$result = mysqli_query($con, $query);
?>
<table class="tableproduct">
<tr>
<th class="thproduct">Order ID</th>
<th class="thproduct">Customer Name</th>
<th class="thproduct">Product</th>
<th class="thproduct">Total Price</th>
<th class="thproduct"></th>
<th class="thproduct"></th>
</tr>
<?php
if( $result ){
while($row = mysqli_fetch_assoc($result)) :
?>
<form method="POST" action="orderhistory.php">
<tr>
<td class="tdproduct"><?php echo $row['order_id']; ?> </td>
<td class="tdproduct"><?php echo $row['customer_name']; ?> </td>
<td class="tdproduct"><?php echo $row['product_name']; ?> </td>
<td class="tdproduct"><?php echo $row['total_price']; ?> </td>
<td class="tdproduct"><a href='editorderhistory.php?id=<?php echo $row['id']; ?>'>EDIT</a></td>
<input type="hidden" name="product_id" value="<? echo $row['id']; ?>"/>
<td class="tdproduct"><input name="delete" type="submit" value="DELETE "/></td>
</tr>
</form>
<?php
endwhile;
}
?>
</table>
<?php
//Count the total records
if ($result != false) {
$total_records = mysqli_num_rows($result);
if ($total_records == 0) {
echo 'No results founds.';
}
}
//Using ceil function to divide the total records on per page
$total_pages = ceil($total_records /$per_page);
?>
<span class="spandarkblue">
<?php
//Going to first page
echo "<center><a href='orderhistory.php?page=1'>".'First Page'."</a> ";
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='orderhistory.php?page=".$i."'>".$i."</a> ";
};
// Going to last page
echo "<a href='orderhistory.php?page=$total_pages'>".'Last Page'."</a></center>";
?>
Any ideas?

Found below issues in you code.
1) You are trying to get page value from URL using POST, where as you need to GET method to fetch values from URl. Using POST is returning null value, so $page value is always set to 1
So use $_GET["page"] instead of $_POST["page"]
2) You are preparing pagination by considering row count of the query which you are executing. But as you have added limits , your $total_records is always equals to $per_page value or less, resulting in only one page number.
Use the following code for generate pazination
$query1 = "SELECT count(*) as totalRecords FROM orders";
$result1 = mysqli_query($con, $query1);
if ($result1) {
$row1 = mysqli_fetch_assoc($result1);
$total_records = $row1['totalRecords'];
if ($total_records == 0) {
echo 'No results founds.';
}
}
Instead of below code
if ($result != false) {
$total_records = mysqli_num_rows($result);
if ($total_records == 0) {
echo 'No results founds.';
}
}
Hope it helps you.

You need to fetch all the data to know the total of your records, then you show only the desired data whithin a for() loop, so remove LIMIT $start, $per_page from your query, in this node you will always have 20 or less results
In your while() save the data in arrays like this:
$index = 0;
while($row = mysqli_fetch_assoc($result)) {
$ordID[$index] = $row["order_id"];
// The rest of your data...
$index++; // Increment the index
}
Then you chan show only the desired data:
for($i = (($page-1)*$perPage); $i < min(($page*$perPage), $total); $i++) {
echo $orderID[$i];
// And so on...
}
The min() function returns the lowest value between two vars, in this way in the last page, if you have 17 products instead of 20 you will not have errors.

Related

PHP SQLSRV Pagination function returns one row

My pagination isn't working correctly. I get the page numbers but each page only has one row when it should have 10 rows. I new to php and am adapting code that I found on this site. When I load the page I can tell by the id number that the result showing is what I would expect the 10th row in the query to be...rows 1-9 are missing.
<?php
//Function to return rows for each page
function getPage($stmt, $pageNum, $rowsPerPage)
{
$offset = ($pageNum - 1) * $rowsPerPage;
$rows = array();
$i = 0;
while(($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC,SQLSRV_SCROLL_ABSOLUTE,$offset + $i)) && $i < $rowsPerPage)
{
array_push($rows, $row);
$i++;
}
return $rows;
}
?>
<?php
// Set the number of rows to be returned on a page.
$rowsPerPage = 10;
$usr = $_SESSION['user'];
if ($_SESSION['admin']="YES") {
$query = "SELECT iID,FirstName,LastName, convert(varchar, SubmitDate, 101) as SubDate,LEFT(ImproveIdea,30) as MyIdea,Status FROM Idea where Status='Pending' ORDER BY iID desc";
}else {
$query = "SELECT iID,FirstName,LastName,convert(varchar, SubmitDate, 101) as SubDate,LEFT(ImproveIdea,30) as MyIdea,Status FROM Idea where SubmitBy='".$usr."' ORDER BY iID desc";
}
$stmt = sqlsrv_query($connect,$query, array(), array( "Scrollable" => 'static' ));
if ( !$stmt )
die( print_r( sqlsrv_errors(), true));
?>
<table class="table table-striped table-bordered">
<thead class="thead-light">
<tr>
<th width="54%" scope="col">Submitted By</th>
<th width="14%" scope="col">Date Submitted</th>
<th width="13%" scope="col">Status</th>
<th width="19%" scope="col">Actions</th>
</tr>
</thead>
<tbody>
<?php
$pageNum = isset($_GET['pageNum']) ? $_GET['pageNum'] : 1;
$page = getPage($stmt, $pageNum, $rowsPerPage);
foreach($page as $row)
$ideanum = $row[0];
$fname = $row[1];
$lname = $row[2];
$submitdate = $row[3];
$idea = $row[4];
$status = $row[5];
echo '<tr>';
echo '<td>'.$ideanum.' '.$fname.' '.$lname.' - '.$idea.'...</td>';
echo '<td>'.$submitdate.'</td>';
echo '<td>'.$status.'</td>';
echo '<td><button type="button" class="btn btn-success"><i class="la la-eye"></i></button><button type="button" class="btn btn-info"><i class="la la-edit"></i></button></td>';
echo "</tr>";
?>
<?php
// Get the total number of rows returned by the query.
// Display links to "pages" of rows.
$rowsReturned = sqlsrv_num_rows($stmt);
if($rowsReturned === false)
die( print_r( sqlsrv_errors(), true));
elseif($rowsReturned == 0)
{
echo "No rows returned.";
exit();
}
else
{
// Display page links.
$numOfPages = ceil($rowsReturned/$rowsPerPage);
for($i = 1; $i<=$numOfPages; $i++)
{
$pageLink = "?pageNum=$i";
print("<a href=$pageLink>$i</a> ");
}
echo "<br/><br/>";
}
?>
</tbody>
</table>
SOLVED: The issue was that I was missing the brackets in my foreach statement as a redditor pointed out to me.

Getting the first row from database refreshes the page continuously

I'm trying to get the first row from phpmyadmin. After trying to do it different ways, I thought I would ask. Right now, the problem is that it is refreshing the browser continuously.
i've tried to add a die, but I'm not very good at mysqli/php
$sql2="SELECT * FROM stellingen WHERE REGIOID=1;";
$records2 = mysqli_query($con, $sql2);
$row = mysqli_fetch_assoc($records2);
while ($stellingen = mysqli_data_seek($records2, 0)){
echo "<p>".$stellingen['Stelling']."</p>";
}
I expect the php to fetch the first data. In the context of a loop where the next data will nneed to come later in the page.
some more code
<div class="stellingen">
<div class="stelling-wrapper" id="btn1">
<img src="images/button.svg" alt="Show more..." class="btn" id="bton">
<p type="button" class="stelling">
<?php
$sql2="SELECT * FROM stellingen WHERE REGIOID=1;";
$records2 = mysqli_query($con, $sql2);
$row = mysqli_fetch_assoc($records2);
while ($stellingen = mysqli_data_seek($records2, 0)){
echo "<p>".$stellingen['Stelling']."</p>";
}
/*
if ($recordscheck2 > 0){
while ($stellingen = mysqli_fetch_assoc($records2)){
echo "<p>".$stellingen['Stelling']."</p>";
}
}*/
?>
</div>
<div id="p1">
<table id="tabel" border=1px class="data">
<tr>
<th>Title</th>
<th>Source</th>
<th>Weight</th>
<th>Date</th>
</tr>
<?php
$sql1="SELECT * FROM stelling WHERE stelling_iD=1;";
$records1 = mysqli_query($con, $sql1);
$recordscheck = mysqli_num_rows($records1);
if ($recordscheck > 0){
while ($stelling = mysqli_fetch_assoc($records1)){
echo "<tr>";
echo "<td>".$stelling['Title']."</td>";
echo "<td>".$stelling['Source']."</td>";
echo "<td>".$stelling['Wheight']."</td>";
echo "<td>".$stelling['Timer']."</td>";
echo "</tr>";
}
}
?>
</table>
</div>
Okey, so your using mysqli_data_seek() in a while() loop, which is wrong...
<?php
if($result = mysqli_query($con, "SELECT * FROM stellingen WHERE REGIOID=1;")) {
mysqli_data_seek($result, 0);
$row = mysqli_fetch_assoc($result);
echo "<p>{$row["Stelling"]}</p>";
}
?>
Should work for you.
[Edit] I corrected my variable names.

multiple checkboxes with paging in php without using javascript and jquery

Good day, I have an HTML table and I use paging on it so that only a certain amount of items is shown. The problem is that I need to have multiple selections with checkboxes and that works for a single page but I need that to work between pages. So for example on page 1 you choose 3 items and in the next page you choose 5 items and when GET happens I need to have all those items in one place so that I can store them in a variable.
<?php
include("connect.php"); //database connection file
$limit = 7;
if ( isset($_GET['page']) ) {
$page_no = $_GET['page'];
} else {
$page_no = 1;
}
$start_from = ($page_no-1)*$limit;
$sql = "SELECT * FROM emp_info LIMIT $start_from,$limit ";
$result = mysqli_query($conn , $sql);
?>
<form method="GET" action="project.php?name=<?php echo
$data['name']; ?>">
<div class="container">
<h2>employee information:</h2>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>EmpId</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<?php
$info = "SELECT * FROM emp_info LIMIT $start_from,$limit ";
//query to select the data from database
$query = mysqli_query ($conn , $info);
while ( $data = mysqli_fetch_assoc ($query) )
{ //query to fetch the data
$_SESSION['emp_name']=$data['name'];
?> <tr>
<td><?php echo $data['emp_id'];?></td>
<td>
<a href="project.php?id=<?php echo $data['emp_id'];?>&name=<?php echo $data['name']; ?>">
<input type="checkbox" name="check_list[]" value="<?php echo $data['name'];?>">
</a> <?php echo $data['name'];?>
</td>
<td><?php echo $data['email'];?></td>
</tr>
<?php }
?>
</tbody>
</table>
<ul class="pagination">
<?php
$sql = "SELECT COUNT(*) FROM emp_info";
$result = mysqli_query($conn , $sql);
$row = mysqli_fetch_row($result);
$total_records = $row[0];
// Number of pages required.
$total_pages = ceil($total_records /
$limit);
$pagLink = "";
for ( $i = 1; $i <= $total_pages; $i++) {
if ( $i == $page_no) {
$pagLink .= "<p>Pages:</p><li class='active'><a href='datatable.php?id=" . $data['emp_id'] .
"&page=" . $i ."'>". $i ."</a></li>";
} else {
$pagLink .= "<li><a href='datatable.php?page=". $i ."'>". $i ."</a></li>";
}
};
echo $pagLink;
?>
</ul>
</div>
<button type="submit" formaction="project.php"
name="select_proj">Select Project</button>
<button type="submit"
formaction="addnewproj.php" name="add_proj">Add New
Project</button>
</form>
</body>
</html>
I recommend reseaching abit of Javascript and more specificly aJax to solve this issue.
You need somewhere to store the information that has been selected in order to use it somewhere else.

PHP Pagination with WHERE Clause

<html>
<body>
<center>
<div>
<form method="post" action="admission_list_fetch5.php">
Enter Cousre Code: <input name="course_code" placeholder="course code">
<input type="submit" name="submit" value="Submit">
</form>
<div>
<table border="2" id="enquirytable" style= "border-collapse:collapse;"">
<thead>
<tr>
<th style="width:50;">SL No</th>
<th>Student ID</th>
<th>Enrol No</th>
<th>Name</th>
<th>Course</th>
<th>Semester</th>
</tr>
</thead>
<tbody>
<?php
//error_reporting(0);
$num_rec_per_page=10;
mysql_connect('localhost','root','');
mysql_select_db('nobledatabase');
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $num_rec_per_page;
$course_code=$_POST['course_code'];
$sql = "SELECT * FROM admission_list where course_code='$course_code' LIMIT $start_from, $num_rec_per_page";
$rs_result = mysql_query ($sql); //run the query
$i=1;
while( $row = mysql_fetch_assoc( $rs_result ) )
{
echo ("<tr><td style='text-align:center'>$i</td>".
"<td>{$row['student_id']}</td>".
"<td>{$row['enrol']}</td>".
"<td>{$row['name']}</td>".
"<td>{$row['course']}</td>".
"<td>{$row['sem_year']}</td></tr>\n");
$i++;
}
?>
</tbody>
</table>
<?php
$sql="SELECT * FROM admission_list where course_code='$course_code'";
$rs_result = mysql_query($sql); //run the query
$total_records = mysql_num_rows($rs_result); //count number of records
$total_pages = ceil($total_records / $num_rec_per_page);
?>
</div><!--enquirytable-->
<div class="enquirypages">
<br>
<?php
echo "<a href='admission_list_fetch5.php?page=1&course_code=$course_code'>".'<<'."</a> "; // Goto 1st page
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='admission_list_fetch5.php?page=".$i."&course_code=$course_code'> ".$i." ";
};
echo "<a href='admission_list_fetch5.php?page=$total_pages&course_code=$course_code'>".'>>'."</a> "; // Goto last page
?>
</div>
</div>
</center>
</body>
</html>
Even if I pass the parameters to all the pages, I am getting the same error message:
Notice: Undefined index: course_code in C:\wamp\www\admission_list_fetch5.php on line 33
When I look at the logic it seems that the only value that supplies the course_code variable comes from the $_POST['course_code']. This means that you have to submit from a form post every time to populate this variable.
The assumption is that the 2nd code peace is the admission_list_fetch5.php.
Whenever paging occurs then clicking on the <a href link passing query strings at no point does course_code get assigned using a $_GET['course_code']. Therefore course_code query string will always be empty.
I would suggest the following on the assumption admission_list_fetch5.php
if(isset($_POST['course_code']))
{
$course_code = $_POST['course_code'];
}
if(isset($_GET['course_code']))
{
$course_code = $_GET['course_code'];
}
Not very elegant but serves the purpose. When you post to this page there should be not query string therefore the code will default to the $_POST['course_code']. If a query string was set for then it will override using $_GET['course_code'].

SESSION Cart adding 2 + or -2 problem

So i edited my own shop but im having some issues with it, for example it add 2 instead of 1 or it removes 2 instead of 1,
you can see how it looks on www.neobotmx.org/test/tienda.php <<< not opwn for the public yet >> thats why its on a test folder
The shop code :
<?php
$product_id = $_GET[id]; //the product id from the URL
$action = $_GET[action]; //the action from the URL
//if there is an product_id and that product_id doesn't exist display an error message
if($product_id && !productExists($product_id)) {
die("Error. Product Doesn't Exist");
}
switch($action) { //decide what to do
case "add":
$_SESSION['cart'][$product_id]++; //add one to the quantity of the product with id $product_id
break;
case "remove":
$_SESSION['cart'][$product_id]--; //remove one from the quantity of the product with id $product_id
if($_SESSION['cart'][$product_id] == 0) unset($_SESSION['cart'][$product_id]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items.
break;
case "empty":
unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart.
break;
}
?>
<?php
if($_SESSION['cart']) { //if the cart isn't empty
//show the cart
echo "<table border=\"1\" align=\"center\" padding=\"3\" width=\"70%\">";
echo "<tr>";
//show this information in table cells
echo "<td align=\"center\"><strong>Producto</strong></td>";
//along with a 'remove' link next to the quantity - which links to this page, but with an action of remove, and the id of the current product
echo "<td align=\"center\"><strong>Cantidad</strong></td>";
echo "<td align=\"center\"><strong>Costo</strong></td>";
echo "</tr>";//format the cart using a HTML table
//iterate through the cart, the $product_id is the key and $quantity is the value
foreach($_SESSION['cart'] as $product_id => $quantity) {
//get the name, description and price from the database - this will depend on your database implementation.
//use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
$sql = sprintf("SELECT name, description, price FROM products WHERE id = %d;",
$product_id);
$result = mysql_query($sql);
//Only display the row if there is a product (though there should always be as we have already checked)
if(mysql_num_rows($result) > 0) {
list($name, $description, $price) = mysql_fetch_row($result);
$line_cost = $price * $quantity; //work out the line cost
$total = $total + $line_cost; //add to the total cost
echo "<tr>";
//show this information in table cells
echo "<td align=\"center\"><strong>$name</strong></td>";
//along with a 'remove' link next to the quantity - which links to this page, but with an action of remove, and the id of the current product
echo "<td align=\"center\"><strong>$quantity </strong>Borrar</td>";
echo "<td align=\"center\"><strong>$line_cost</strong></td>";
echo "</tr>";
}
}
//show the total
echo "<tr>";
echo "<td colspan=\"2\" align=\"right\"><strong>Total</strong></td>";
echo "<td align=\"right\"><strong>$total</strong></td>";
echo "</tr>";
echo "</table>";
}else{
//otherwise tell the user they have no items in their cart
echo "No tiene articulos en compra.";
}
//function to check if a product exists
function productExists($product_id) {
//use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
$sql = sprintf("SELECT * FROM products WHERE id = %d;",
$product_id);
return mysql_num_rows(mysql_query($sql)) > 0;
}
?>
</p>
<p><strong>Seguir Comprando</strong></p>
<?php
and now the display of the books / items / whatever you want.
<?php
define('MAX_REC_PER_PAGE', 1);
$sql = "SELECT id, name, description, price FROM products;";
$rs = mysql_query("SELECT COUNT(*) FROM products") or die("Imposible Realizar Operacion");
list($total) = mysql_fetch_row($rs);
$total_pages = ceil($total / MAX_REC_PER_PAGE);
$page = intval(#$_GET["page"]);
if (0 == $page){
$page = 1;
}
$start = MAX_REC_PER_PAGE * ($page - 1);
$max = MAX_REC_PER_PAGE;
$rs = mysql_query("SELECT id, name, description, price FROM products ORDER BY id
ASC LIMIT $start, $max") or die("Imposible Realizar Operacion");
?>
<table width="100%" height="404" border="0" cellpadding="12">
<?php
while (list($id, $name, $description, $price) = mysql_fetch_row($rs)) {
?>
<tr>
<td height="46" align="left" valign="middle"><p><strong> Producto :
<?= htmlspecialchars($name) ?>
</strong>
</p></td>
</tr>
<tr>
<td height="172" align="left" valign="middle"><p><strong>Descripcion :</strong></p>
<p>
<strong>
<?= htmlspecialchars($description) ?>
</strong></p></td>
</tr>
<tr>
<td height="67" align="left" valign="middle"><p><strong>Precio :
<?= htmlspecialchars($price) ?> </strong>
</p></td>
</tr>
<tr>
<td height="109" align="center" valign="middle"><strong><? echo "Comprar" ?> </strong></td>
</tr>
<?php
}
?>
</table>
<table border="0" cellpadding="5" align="center">
<tr>
<td><strong>Pagina : </strong></td>
<?php
for ($i = 1; $i <= $total_pages; $i++) {
$txt = $i;
if ($page != $i)
$txt = "$txt";
?>
<td align="center"><?= $txt ?></td>
<?php
}
?>
</table>
I have no idea where's the error on it...
Ty for the help :)
Obiusly you have to :
<?php session_start();?>
include your database
etc
You have in the style:
body {
background-image: url();
}
which is causing the browser to request the page again, which adds it to the cart again.
Instead of rendering the cart page, Once the code has modified the cart it should send a redirect to the cart page.

Categories