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.
Related
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.
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.
SO i have form which consist of "Event Name" "Event Description" "Event Date" and checkbox "is important". When i check checkbox value "yes" its important, it sends to the sql value = "1" to table "is_important". Everything is all right, but i give the bootstrap style "bg-danger" for that "is_important" = 1 table and it doesnt show up. What's the problem?
You can see in the code:
<?php
if (isset($_POST['important'])) {
$error = array();
$success = array();
$eventTime = time();
$important = $_POST['important'];
$eventName = trim(mysql_real_escape_string($_POST['EventName']));
$eventDesc = htmlentities(trim(mysql_real_escape_string($_POST['EventDesc'])), ENT_QUOTES);
if (!isset($eventName) || empty($eventName)) {
$error['eventName'] = "Prasome ivesti ivykio varda";
} else if (strlen($eventName) > 32 || strlen($eventName) < 3) {
$error['eventName'] = "Ivykio pavadinimas turi buti tarp 3 ir 32 simboliu";
}
if (!isset($eventDesc) || empty($eventDesc)) {
$error['eventDesc'] = "Prasome ivesti ivykio aprasyma";
}
if (empty($error)) {
$sql = "INSERT INTO notes_list (title, description, timestamp,is_important) VALUES ('$eventName', '$eventDesc','$eventTime','$important')";
$result = mysqli_query($con, $sql);
$success[] = "SEKME !";
} else {
}
}
?>
<table class="table table-striped">
<thead>
<tr>
<th>Event name</th>
<th>Event description</th>
<th>Event date</th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM notes_list ORDER BY id DESC LIMIT 10";
$result2 = mysqli_query($con, $query);
print_r($_POST);
if ($result2) {
while ($note = mysqli_fetch_assoc($result2)) {
?>
<tr<?php echo (($note['is_important'] == 1) ? "class='bg-danger'" : ""); ?>>
<td><?php echo $note['title']; ?></td>
<td><?php echo $note['description'] ?></td>
<td><?php echo date('l M jS', $note['timestamp']); ?></td>
</tr>
<?php
}
mysqli_free_result($result2);
}
/* close connection */
mysqli_close($con);
?>
</tbody>
</table>
Full Example in this picture:
https://www.dropbox.com/s/h650h2spy2487dm/chechbox.jpg?dl=0
This:
<tr<?php echo (($note['is_important'] == 1) ? "class='bg-danger'" : ""); ?>>
would render this:
<trclass='bg-danger'>
in case is_important is 1. You need a space there, before the class.
I'm trying to get an id from the users database so that I can link to about.php?id=$id1 and I'm using 2 while loops to do that. I end up getting what I want, about.php?id=$id1 but there are duplicate entries...
Here's the code.
<?php
require("connect.php");
require("header.php");
$max = 5; //amount of articles per page. change to what to want
$p = $_GET['p'];
if(empty($p))
{
$p = 1;
}
$limits = ($p - 1) * $max;
//view the news article!
$id = isset($_GET['id']) ? $_GET['id'] : false;
if($id && is_numeric($id)){
$id = $_GET['id'];
$sql = mysql_query("SELECT * FROM blogdata WHERE id = '$id'");
while($r = mysql_fetch_array($sql))
{
echo $total;
$id = $r['id'];
$date = $r['date'];
$title = $r['title'];
$content = $r['content'];
$email = $r['author_email'];
$cat = $r['category'];
$author = $r['author'];
$query1 = mysql_query("SELECT * FROM users");
while ($row1 = mysql_fetch_array($query1)){
$id1 = $row1['id'];
echo "<center>
<table border='0' width='100%' cellspacing='10'>
<tr>
<td width='20%' valign='top'><div class='title'>$title</div>
<div class='info'><i>$date</i><br />
By <a href='$id1'>$author</a><br />
$cat</div>
</td>
<td width='80%' valign='top'>";
echo nl2br($content);
echo "</td>
</tr>
</table>
<hr />
<a href='index'>← Rewind.</a>
</center>";
}
}
}else{
//view all the news articles in rows
$sql = mysql_query("SELECT * FROM blogdata ORDER BY id DESC LIMIT ".$limits.",$max") or die(mysql_error());
//the total rows in the table
$totalres = mysql_result(mysql_query("SELECT COUNT(id) AS tot FROM blogdata"),0);
//the total number of pages (calculated result), math stuff...
$totalpages = ceil($totalres / $max);
while($r = mysql_fetch_array($sql))
{
$id = $r['id'];
$date = $r['date'];
$title = $r['title'];
$content = $r['content'];
$email = $r['author_email'];
$cat = $r['category'];
$author = $r['author'];
$query1 = mysql_query("SELECT * FROM users");
while ($row1 = mysql_fetch_array($query1)){
$id1 = $row1['id'];
echo "<center>
<table border='0' width='100%' cellspacing='10'>
<tr>
<td width='20%' valign='top'><div class='title'>$title</div>
<div class='info'><i>$date</i><br />
By <a href='$id1'>$author</a><br />
$cat</div>
</td>
<td width='80%' valign='top'>";
echo nl2br($content);
echo "</td>
</tr>
</table>
<hr />
</center>";
}
}
//close up the table
echo "</tr></table><center>";
$page = $_GET['p'];
for($i = 1; $i <= $totalpages; $i++)
{
if ( $page == $i ) {
echo "<b>$i</b>";
} else {
echo "<a href='?p=$i'>$i</a>";
}
if ($i < $totalpages)
echo " <font color=\"#666\">•</font> ";
}
}
echo "<br />";
require("footer.php");
?>
Couldn't fully get your question, but does SELECT DISTINCT column_name FROM table help you? It selects only distinct rows from a table.
<?php
include "includes/connection.php";
//$id=$_REQUEST['category'];
//$catid=mysql_escape_string($id);
$catid = isset($_GET['category']) ? (int)$_GET['category'] : 0;
$recordsPerPage =4;
# 0
// //default startup page
$pageNum = 1;
if(isset($_GET['p']))
{
$pageNum = $_GET['p'];
settype($pageNum, 'integer');
}
$offset = ($pageNum - 1) * $recordsPerPage;
//set the number of columns
$columns = 1;
//set the number of columns
$columns = 1;
$query = "SELECT temp_id, temp_img, temp_header, temp_resize, temp_small, temp_name, temp_type, cat_id, col_id, artist_id FROM `templates` where cat_id = '{$catid}' ORDER BY `temp_id` DESC LIMIT $offset, $recordsPerPage";
$result = mysql_query($query);
//we add this line because we need to know the number of rows
$num_rows = mysql_num_rows($result);
echo "<div>";
//changed this to a for loop so we can use the number of rows
for($i = 0; $i < $num_rows; $i++) {
while($row = mysql_fetch_array($result)){
if($i % $columns == 0) {
//if there is no remainder, we want to start a new row
echo "<div class='template'>";
}
echo ...........my data(s).
if(($i % $columns) == ($columns - 1) || ($i + 1) == $num_rows) {
echo "</div>";
}
}
}
echo "</div>";
//}
?>
<div class="pagination">
<?
$query = "SELECT COUNT( temp_id ) AS `temp_date` FROM `templates` where cat_id ='{$catid}'";
$result = mysql_query($query) or die('Mysql Err. 2');
$row = mysql_fetch_assoc($result);
$numrows = $row['temp_date'];
//$numrows = mysql_num_rows($result);
$self = $_SERVER['PHP_SELF'];
$maxPage = ceil($numrows/$recordsPerPage);
$nav = '';
for($page = 1; $page <= $maxPage; $page++)
{ if ($page == $pageNum)
{
$nav .= "<span class=\"pegination-selected\">$page</span>";
}
else
{
$nav .= "<aa class=\"pegination\" hreeef=\"javascript:htmlData('$self','p=$page')\">$page</a>";
}
}
if ($pageNum > 1)
{
$page = $pageNum - 1;
$prev = "<aa class=\"pagination\" hreeef=\"javascript:htmlData('$self','p=$page')\"><strong><imgee src=\"images/previous.gif\" alt=\"previous\" width=\"5\" height=\"10\" border=\"0\"/></strong></a>";
$first = "<aa class=\"pagination\" hreeef=\"javascript:htmlData('$self','p=1')\"><strong><imgee src=\"images/previous1.gif\" alt=\"first\" width=\"7\" height=\"10\" border=\"0\" /></strong></a>";
}
else
{
$prev = '<strong> </strong>';
$first = '<strong> </strong>';
}
if ($pageNum < $maxPage)
{
$page = $pageNum + 1;
$next = "<aa hreeef=\"javascript:htmlData('$self','p=$page')\"> <strong> <imgee src=\"images/next.gif\" alt=\"next\ width=\"5\" height=\"10\" border=\"0\" /></strong></a>";
$last = "<a class=\"pagination\" hreeef=\"javascript:htmlData('$self','p=$maxPage')\"> <strong> <imgee src=\"images/next1.gif\" alt=\"next\" border=\"0\" width=\"7\" height=\"10\" /></strong></a>";
}
else
{
$next = '<strong> </strong>';
$last = '<strong> </strong>';
}
echo "<div class=\"pagination\"> $first $prev <span class=\"pagination-selected\">$nav </span> $next $last </div>";
?>
Here my ajax code:
function GetXmlHttpObject(handler)
{
var objXMLHttp=null
if (window.XMLHttpRequest)
{
objXMLHttp=new XMLHttpRequest()
}
else if (window.ActiveXObject)
{
objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("txtResult").innerHTML=xmlHttp.responseText
}
else
{
//alert(xmlHttp.status);
}
}
function htmlData(url, qStr)
{
if (url.length==0)
{
document.getElementById("txtResult").innerHTML="";
return;
}
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
url=url+"?"+qStr;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true) ;
xmlHttp.send(null);
}
How can I get the selected category id after 1st page in pagination?
Do you pass though category in the request? You haven't given us that information (what is the value of qstr in the javascript?), but I'd guess not.
You're also passing it straight into an SQL query, which leaves you open to injection.
You should use mysql_escape_string() to fix that.
Post it with the AJAX call and return it
Store it in a local JS variable
Add it to the URL
...
You seem to be aware that $_GET['p'] gets the value of the 'p' parameter passed in the querystring. Well $_REQUEST['category'] is doing the same thing. (Technically $_REQUEST checked everything in $_POST, $_GET and $_COOKIE).
So if you haven't set the 'category' in the querystring then it wont contain anything in your code.
You should add ?category=XXX&sid=RAND... to your url
Better use $category = isset($_GET['category']) ? (int)$_GET['category'] : 0;
<?php
include ('database connection file ');
?>
**and this is my index.php**
<?php
if(isset($_GET['page']))
{
$page=$_GET['page'];
$offset=$limit * ($page - 1);
}
else{
$page=1;
$offset=0;
}
if($page==0 || $page > $page_rec){
header('location:index.php?page=1');
}
?>
<body>
<div>
<div class="headingSec"> <h1 align="center">Welcome AdminLogout</h1>
<p align="center">Manage your student database here.</p></div>
<table class="trBgColr">
<thead class="bgColorSec">
<th>Registration Id</th>
<th>Image</th>
<th>Signature</th>
<th>Name</th>
<th>Father's Name</th>
<th>City</th>
<th>Registration Category</th>
<th>Phone Number</th>
<th>Mobile Number</th>
<th>Status</th>
<th>
</thead>
<?php
//$getstudentdetails = "select * from student_details";
$result=mysqli_query($conn,"select * from `student_details` LIMIT $offset,$limit");
/* fetch associative array */
while($row = mysqli_fetch_array($qry)) {
?>
<tr>
<td><?php echo $row["registration_number"]; ?>
<td><?php echo $row["Name"]; ?></td>
<td><?php echo $row["Father_Name"]; ?></td>
<td><?php echo $row["City"]; ?></td>
<td><?php echo $row["Registration_Category"]; ?></td>
<td><?php echo $row["Phone_Number"]; ?></td>
<td><?php echo $row["Mobile_Number"]; ?></td>
<?php if($row['payment_status']==1)
{?>
<td><?php echo "Sucsess"; ?></td>
<?php
}
else{
?>
<td><?php echo "Failed"; ?></td>
<?php
}?>
<?php
}
$pre=$page - 1;
$next=$page + 1;
?>
</tr>
</table>
</div>
<br />
<br />
<div class="pagination">
<?php
for($i=1;$i<=$page_rec;$i++){
continue;
?>
<?php $i;?>
<?php } ?>
Previous«
Next»