I am creating a page for someone where it will display all orders in the database, limited to 10 per page.
It works to that end, but now the issue is when I try to get a max number of pages using the below code:
$msql = "SELECT * FROM orders";
$mresult = $db->query($msql);
if(is_object($mresult) && $mresult->num_rows > 0)
{
if($mresult->num_rows > 10)
{
$maxpage = $mresult->num_rows / 10 + 1;
}
else
{
$maxpage = 1;
}
}
It won't set the $maxpage variable to anything other than 1 unless there are 20 or more orders in the database.
Right now, I have 11 test orders in the database, so when it divides by 10, it should set max pages to 1, + 1 additional page since there are more than 10 orders.
I have scoured the web looking for a solution, and have came up empty handed. Any thoughts or suggestions?
EDIT:
Added code at bottom of the table the actual orders are displayed for further troubleshooting:
<tr>
<td colspan="2" align="left"><<<< Prev</td>
<td align="center">Page <?php if(isset($_GET['page'])) { echo $_GET['page'] . ' of ' . $maxpage; } else { echo '1 of 1'; } ?></td>
<td colspan="2" align="right">Next >>>></td>
</tr>
Your code is running fine, the problem is your statement, the statement where you are dividing by 10, should be within parenthesis, because that needs to be computed first, then add 1 to it, in your code, addition is being done which equals 11, and then 11/11 = 1;
you probably should wrap it within floor function as well.
if($mresult->num_rows > 10)
{
$maxpage = (floor($mresult->num_rows / 10)) + 1;
}
else
{
$maxpage = 1;
}
Please use below code, I have tested.
$query = "select * from orders";
$history_res = mysql_query($query);
//count records
$totrecords = mysql_num_rows($history_res);
$totpages = ceil($totrecords / 10);
return $totpages;
Implementing the code provided by #Talha, and changing my navigation controls to the following fixed the issue:
<tr>
<td colspan="2" align="left"><<<< Prev</td>
<td align="center">Page <?php echo $page . ' of ' . $maxpage; ?></td>
<td colspan="2" align="right">Next >>>></td>
</tr>
Related
So I have this code setup to display food entries by expiration dates on a table, from top to bottom, earliest to latest. If they are within three days of the current date, the text will be yellow,if it is anytime after that, the text will be red.
Anyway, I recently was testing and realized that if two entries have the same date, the way I have my code setup, it would pull show only one of the entries however number of times that expiration date is on the table (the very first entry with that date added to be exact).
So I setup a for loop uses some queries to check if there were more than one entries and then displayed each one subsequently. Problem is, I get to the final index for the loop, and the Name associated with that date will not show up. Heres the Code:
<?php
$sql1=mysql_query("SELECT email from loggedin WHERE session_id='$userid'");
$sess=mysql_fetch_array($sql1);
$newValue=$sess['email'];
$sqlLength = mysql_query("SELECT * FROM food WHERE OwnerEmail='$newValue'");
?>
<div class="table-responsive">
<h2 class="sub-header">Expiration Dates</h2>
<table class="table table-striped">
<thead>
<tr>
<th>Food Name</th>
<th>Brand Name</th>
<th>Food Group</th>
<th>Location</th>
<th>Expiration Date</th>
</tr>
</thead>
<tbody>
<?php
$i = 0;
while($test = mysql_fetch_array($sqlLength)){
$dates[$i] = $test['ExpirationDate'];
$i++;
}
$length=count($dates);
for($x=0;$x<$length;$x++){
$year[$x]=substr($dates[$x],6,4);
$month[$x] = substr($dates[$x],3,2);
$day[$x] = substr($dates[$x],0,2);
}
for($x=0;$x<$length-1;$x++){
for($y=$x+1;$y<$length;$y++){
if($year[$x] > $year[$y]){
$temp=$year[$x];
$year[$x]= $year[$y];
$year[$y]=$temp;
$temp=$month[$x];
$month[$x]= $month[$y];
$month[$y]=$temp;
$temp=$day[$x];
$day[$x] = $day[$y];
$day[$y] = $temp;
}
elseif($year[$x] == $year[$y]){
if($month[$x] > $month[$y]){
$temp=$month[$x];
$month[$x]= $month[$y];
$month[$y]=$temp;
$temp=$day[$x];
$day[$x] = $day[$y];
$day[$y] = $temp;
}
elseif($month[$x] == $month[$y]){
if($day[$x] > $day[$y]){
$temp=$day[$x];
$day[$x] = $day[$y];
$day[$y] = $temp;
}
}
}
}
}
for($x=0;$x<$length;$x++){
$orderedDates[$x]= "$day[$x]-$month[$x]-$year[$x]";
}
$currentYear=date("Y");
$currentMonth=date("m");
$currentDay=date("d");
$multiple="false";
for($x=0;$x<$length;$x++){
$class='';
if($multiple=="false"){
$sql2 = mysql_query("SELECT * FROM food WHERE OwnerEmail='$newValue' AND ExpirationDate='$orderedDates[$x]'") or die(mysql_error());
$rows = mysql_fetch_array($sql2);
if(count($rows) > 7){
$y=1;
$multiple="true";
$count=count($rows)/7;
}
}
else{
$rows = mysql_fetch_array($sql2);
$y++;
//$x++;
}
$year=substr($rows['ExpirationDate'],6,4);
$month=substr($rows['ExpirationDate'],3,2);
$day=substr($rows['ExpirationDate'],0,2);
if($year==$currentYear){
if($month==$currentMonth){
if(($day - $currentDay) <= 3){
$class='expBad';
}
}
}
if($currentYear > $year){
$class='expGross';
}
elseif($currentYear == $year){
if($currentMonth > $month){
$class = 'expGross';
}
elseif($currentMonth == $month){
if($currentDay > $day){
$class='expGross';
}
}
}
?>
<tr>
<td><b><?php echo $rows['Name'] ?></td>
<td><b><?php echo $rows['Brand'] ?></td>
<td><b><?php echo $rows['Type'] ?></td>
<td><b><?php echo $rows['Container'] ?></td>
<td><b><?php echo "<span class=\"$class\">".$rows['ExpirationDate']."</span>" ?></td>
</tr>
<?php
if($y == $count){
$multiple="false";
}
}
/*
$er=mysql_query("SELECT Name FROM food WHERE ExpirationDate='$orderedDates[3]'");
$der = mysql_fetch_array($er);
$mer=$der['Name'];
echo $mer;
*/
?>
</tbody>
</table>
Some info to know, my food table has 7 columns.
orderedDates gives me a correctly ordered array (I know there's a better way to do that, but I was just starting php when I wrote that)
There are 4 food entries.
Here's the problem, when I get to $x = 3, for some reason it does not display any of the column values for that entry.
Here are what the entries should look like in the table.
what s Grains Pantry 12-02-2012
why s Grains Pantry 12-02-2012
who s Grains Pantry 08-04-2014
where s Grains Pantry 10-04-2014
I only get the first 3 entries and then the 4th row is empty.
the other two columns are id and OwnerEmail
It turns out the count() function was returning back a number other than what I thought.
Which is I thought $count would equal 1 for the value that had a unique expiration date.
But instead it was 2, which caused it to run the mysql_fetch_array function one more time than I wanted,making it point at a null value;
instead I used the following code to get the number of food items with same dates:
$sql2 = mysql_query("SELECT Name FROM food WHERE OwnerEmail='$emailname' AND ExpirationDate='$orderedDates[$x]'") or die(mysql_error());
$count2=0;
while($rows2 = mysql_fetch_array($sql2)){
$count2++;
}
I've been to this site several times before for help which I've managed to solve problems encountered in the past but this time I think I'm going to actually have to ask my own question.
I am working on a system in which employees of a small company can put in their appointments they had every week of the month, including the appointments, number of sales and amount of money made from them. I already calculated things like the success percentage and everything.
Now here lies the problem:
I need to make it so that the week numbers are automatically calculated rather than just put in 5 weeks a month.(Currently it works like: January 1-5 February 5 - 10 and so forth) And the numbers need to be linked to a page where the user can edit the information of that week.
I already know how to make a page like this too, the only thing I really need help with is finding out how to best put the week numbers in properly. (Security not being really an issue because it runs on an internal web server.)
Here's the table segment of my calendar.php :
<table id='myTable' width="600" border="1" cellspacing="3">
<tr>
<th align="left">
Prev </th>
<th colspan='3' width="200"><?php echo $monthNames[$cMonth-1].' '.$cYear; ?></th>
<th align="right"> Next </th></tr>
<?php
echo "<tr align='center'>";
//Rather than a loop, need to get the amount of weeks in each month.
$startingMonthWeekNum = ((($cMonth-1)*5)+1);
$endingMonthWeekNum = ($cMonth*5+1);
echo "<tr><th>Week #</th><th>Afspraken</th><th>Sales</th><th>Omzet</th><th>Conversie %</th></tr>";
for($i = $startingMonthWeekNum; $i < $endingMonthWeekNum; $i++)
{
//Reset variables
$appointments = null;
$sales = null;
$revenue = null;
$conversie = null;
$result = mysqli_query($con, "SELECT * FROM cms_appointments where date_week = $i and date_year = $cYear and id_user = $userId group by date_week");
$sumAppointments = 0;
$sumSales = 0;
$sumRevenue = 0;
while($row = mysqli_fetch_array($result))
{
$weekRow = $row['date_week'];
$appointments = $row['appointments'];
$sales = $row['sales'];
$revenue = $row['revenue'];
$conversie = $appointments > 0 ? ($sales / $appointments)*100 : 0;
}
$sumAppointments += $appointments;
$sumSales += $sales;
$sumRevenue += $revenue;
echo "<tr align='center'>";
echo "<td>$i</td><td>$appointments</td><td>$sales</td><td>$revenue</td><td>$conversie</td>";
echo "</tr>";
}
echo "<tr align='center'><td>Total</td><td>$sumAppointments</td><td>$sumSales</td><td>$sumRevenue</td><td>".($sumAppointments > 0 ? ($sumSales / $sumAppointments)*100 : 0)."</td></tr>";
echo "</tr> </table>";
mysqli_close($con);
?>
I have a small database behind this with the table cms_appointments having all the information in them which are used in this code. The appointments, sales and revenue.
This is the first time I posted a question and if it can be improved in some way, I will try my best to make it easier as this site helped me out greatly in the past, I want to leave this as a well explained first question.
In my pagination code, I list 5 buildings per page and number them from 1 to 5,
<?php
$page = intval($_GET['page']);
if(!$page) $page = 1;
$totalno=mysql_num_rows(mysql_query("SELECT M1_ID FROM M1Buildings WHERE M1_Cat2 BETWEEN 3 AND 4 && M1_Status=5"));
$limit = 5;
$show = $page * $limit - $limit;
$buildinglist = mysql_query("SELECT * FROM M1Buildings WHERE M1_Cat2 BETWEEN 3 AND 4 && M1_Status=5 ORDER BY M1_Height DESC LIMIT $show,$limit",$con);
$firstrowno=1;//This will be 1 for page 1, 6 for page 2, 11 for page 3 etc..
?>
Some html code here, then:
<?php
$startno=1;//This is the number of each row, starting from 1
while ($rowblist = mysql_fetch_array ($buildinglist))
{
echo '<tr>
<td>'.$startno.'</td>
<td>Some information here</td>
<td>Some information here</td>
</tr>';
$startno++;
$firstrowno+5;
}
?>
There is no problem in first page, but when I pass to page 2, it again starts from 1, but I want it starts from 6, I couldn't get how can I achieve it. I've performed a search, but no result. Actually with my limited english, I can't know how to search it with proper words, I guess. Thanks for your understanding!
You need to update your query to use offset. (** Sorry, didn't notice you were using the shorthand **)
Took a moment for me to get the gist of the question.
Use:
$startno = $show + 1;
instead of:
$firstrowno= 1;
After the HTML:
<?php
while ($rowblist = mysql_fetch_array ($buildinglist))
{
echo '<tr>
<td>'.$startno.'</td>
<td>Some information here</td>
<td>Some information here</td>
</tr>';
$startno++;
}
?>
The variables do not retain their state between trips to the server. (Unless you store them and retrieve them from sessions.
I am not a well-versed programmer so i don't want to use a complicated pagination. Is there an alternative to using a pagination like in my queries can i limit them to say 20 results and then if their are more than 20 results i can show a "next" button and then that button will further load the next results??
I only want "next" to show if there are 20> results? Any help will be appreciated. Thanks.
Code:
$query="SELECT * FROM actresses where actress_id = '$actressid' and production_full_name LIKE '%$q%'";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
echo "";
$i=0;
while ($i < $num) {
$1=mysql_result($result,$i,"production_full_name");
$2=mysql_result($result,$i,"production_id");
$3=mysql_result($result,$i,"actress");
echo "<br><div id=linkcontain><a id=slink href=$data/actress.php?id=$2>$3</a><div id=production>$1</div></div>";
echo "";
$i++;
}
You could add a limit to your query.
$lower_limit = $results_per_page * $page_number;
$upper_limit = $lower_limit + $results_per_page
..and production_full_name LIKE '%$q%' LIMIT $lower_limit, $upper_limit
Then make a conditional "next page" link
if ($upper_limit > 20) echo 'Next;
You can find many examples searching on google.
http://www.php-mysql-tutorial.com/wikis/php-tutorial/paging-using-php.aspx for example.
You only have to edit $rowsPerPage for amount of results, and if you want further edit on what to get from the DB, the $query.
Includes are not necessary, though.
edit: note the implication of using a $_GET that will have influence on the DB query. You have to be careful to not allow dangerous values in it (mysql injection). In the example of the webpage, it uses ceil, so I believe that it will output 0 for a non numeric value, which is safer.
You can use the PEAR packages.
They are much easier to use similar to the frameworks.
But before you use them you need to check whether the PEAR works on your server or not.
If you are using it locally then there are steps to install the PEAR packages on your local machine. For more instructions to install PEAR.
Click here to view the installation steps.
Once you have installed the PEAR package please follow the instruction to configure the PAGER class.http://www.codediesel.com/php/simple-pagination-in-php/
J
Something like that:
$data = mysql_query("SELECT * FROM `table`");
$total_data = mysql_num_rows($data);
$step = 30;
$from = $_GET['p'];
$data = mysql_query("SELECT * FROM `table` LIMIT '.$from.','.$step.'"
And creating links:
$p=1;
for ($j = 0 ; $j <= $total_data+$step; $j+=$step)
{
echo ' '.$p.' ';
$p++;
} ?>
Not tested.
If your query is set up as
"SELECT SQL_CALC_FOUND_ROWS * FROM actresses where actress_id = '$actressid' and production_full_name LIKE '%$q%' LIMIT ".($page*$lpage).",".$lpage
... the next statement can be SELECT FOUND_ROWS() to get the actual number of results.
Don't forget to put mysql_real_escape_string() on those variables.
NEVER use SELECT * with mysql_num_rows; if it's a big table, it will waste a LOT of time.
What you can do is fetch a COUNT(*) of how many rows are in your set of data. Then decide how many items you want per page. $numberOfRows / $itemsPerPage gives you the number of pages. In MySQL, to limit results you use LIMIT X, Y X is the beginning of the range, and Y is the number of items you want to fetch. So to fetch all the items on a page, your query would be LIMIT ($currentPage * $itemsPerPage), $itemsPerPage Then it's up to you, depending on how you want to format your pagination, to write the view logic. Just go from back to front: if the current page is 1, then the previous button is disabled. If the page is not 1, then the current page number is the number of pages from the beginning. If the total number of pages is bigger than the current page, then count from the current page, until the last page (unless you want to cut off the page count at some point)
I use the following method to assist in creating a list of pages, no matter what direction. I could plug in 5 for the current page, and 0 as the goal page, and it would return a list of 5 pages for me to iterate through, in order.
/*
* Generates a list of pages based on the current page to the goal page number
*/
function generatePageList($currentPage, $goal) {
$span = $goal - $currentPage;
$step = abs($span) / $span;
$list = array();
for($x = $currentPage; $x !== $goal;) {
// We want to add the step at the beginning of the loop, instead of
// at the end
// Fixes bug when there are only two pages
$x += $step;
$list[] = $x;
}
return $list;
}
This is more easy way to create pagination of a data
<?php
require_once 'db_connect.php';
$limit = 20;
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $limit;
$sql = "SELECT * FROM employee ORDER BY id ASC LIMIT $start_from, $limit";
$rs_result = mysqli_query($con, $sql);
?>
<table class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Salary</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($rs_result)) {?>
<tr>
<td><?php echo $row["employee_name"]; ?></td>
<td><?php echo $row["employee_salary"]; ?></td>
<td><?php echo $row["employee_age"]; ?></td>
</tr>
<?php
};
?>
</tbody>
</table>
<?php
$sql = "SELECT COUNT(id) FROM employee";
$rs_result = mysqli_query($con, $sql);
$row = mysqli_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / $limit);
$pagLink = "<nav><ul class='pagination'>";
for ($i=1; $i<=$total_pages; $i++){
$pagLink .= "<li><a href='index.php?page=".$i."'>".$i."</a></li>";
};
echo $pagLink . "</ul></nav>";
?>
<script type="text/javascript">
$(document).ready(function(){
$('.pagination').pagination({
items: <?php echo $total_records;?>,
itemsOnPage: <?php echo $limit;?>,
cssStyle: 'light-theme',
currentPage : <?php echo $page;?>,
hrefTextPrefix : 'index.php?page='
});
});
</script>
Below is a code for my pagination. The problem that I am having is that the page count is displayed correctly but when I click on page 2 onwards I just get a blank page.
<?php
if (isset($_POST['edit'])) {
if (empty($_GET['page'])) {
$page=0;
}
else {$page = (int)$_GET['page'];}
if ($page == 0){ $page = 1;}
if (ob_get_level() == 0) ob_start();
$per_page = 10;
$p = ($page - 1) * $per_page;
$sql="select * from tba where word='$word' order by id DESC limit ".$p.",".$per_page;
$result=mysql_query($sql) or die(mysql_error());
while ($row=mysql_fetch_array($result)) {
$id=$row['id'];
$word=$row['word'];
$pr=$row['pr'];
if ($pr==0) {
}
else {
?>
<td><span class="style5"><?php echo $id; ?> </span></td>
<td><span class="style5"><?php echo $word?></span></td>
<?php
}
$pages = floor($total / $per_page) + ($total%$per_page>0?1:0);
?>
<center>
<?php
}
for ($i=1;$i<=$pages;$i++) {
print "<a href='?page=".$i."'>".$i."</a> ";
}
echo "<br>You are in page ".$_GET['page'];
}
can some one please tell me what the problem is?
It's time to learn debugging.
As a matter of fact, we can only guess what is going wrong.
While it is only programmer oneself who can tell it for sure. It's their job and duty.
The art of finding what is going wrong is called debugging.
To do it, you have to check every operation result.
For example, does your query return any results?
If not - why? Where does that $word variable come from? But on the second page?
You have to pass all required data to other pages as well as $page variable.
It looks like the $pages = floor... line is inside the while loop, which is the first problem. Also, $total is never being set.
The variable $total is never set making the total pages count incorrect
You need to fetch first the total number of rows with a query similar to:
$sql="SELECT COUNT(id) AS rows FROM tba where word='$word'";
Instead of doing the "floor" operation and adding "1" when has "other page" you can use "ceil"
Instead of:
$pages = floor($total / $per_page) + ($total%$per_page>0?1:0);
You can use:
$pages = ceil($total / $per_page);
Well, the whole output is in an if statement and you didn't posted the POST parameters ($_POST['edit'])