I am going to create a pagination then
$num_row = mysqli_num_rows($res);
total I have 240 rows then:
if($num_row>5){
$count=0;
$index=1;
while($count < $num_row && $index < 5){ ?>
<button id="<?php echo $count; ?>" class="index_b"><?php echo $index; ?></button>
<?php
$count = $count + 5;
$index++;
}
}
I want first 1 2 3 4 5 then next button so I tried
<div class="next_index_b">
<?php if($num_row > 50){?>
<button class="next_membd_index_button" name="50" ><img src="images/arrow.png" /></button>
<?php } ?>
Now my issue is after 4th pagination number, no number is working.
Don't use mysqli_num_rows()! Ideally, you should pull ONLY the data that you're looking for, and then run 2 separate queries. One to fetch the full count, and one to fetch the items per page:
$db = new PDO(...);
$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
$offset = ($page-1) * 50;
$count = $db->query("SELECT COUNT(*) FROM table")->fetchColumn();
$trans = $db->prepare("SELECT * FROM table LIMIT :offset, 50");
$trans->bindValue(':offset', $offset, PDO::PARAM_INT);
$trans->execute();
while ($row = $trans->fetchRow()) {
// echo data
}
//Add footer here. Use $page variable and $count to determine how many pages are available.
while($count < $num_row && $index < 5){ ?>
This condition means that when $index equals 5, the loop is stopped
Therefore, the button with 5 will never be shown.
Try using less or equal than instead of less than
if($num_row>5){
$count=0;
$index=1;
while($count < $num_row && $index <= 5){ ?>
<button id="<?php echo $count; ?>" class="index_b"><?php echo $index; ?></button>
<?php
$count = $count + 5;
$index++;
}
}
Or even better, switch to #FrankerZ's solution
Related
I am fetching username and Id from the database. I have more than 500 usernames. I have to display pagination number only 1 to 5 and last pagination number.
Example:- pagination number is:- 1 2 3 4 5...20(last number).
Now I am getting all numbers in horizontal. Would you help me in this?
Can anyone help me with NEXT and LAST in pagination?
include('../db/connection.php');
$reclimit = 3;
if(isset($_GET['page'])){
$page = $_GET['page'];
} else {
$page = 1;
}
$start = (($page-1) * $reclimit);
$sql = "SELECT * FROM request";
$records =$conn->query($sql);;
$total = $records->num_rows;
$tpages = ceil($total / $reclimit);
$search_sql="SELECT * FROM request LIMIT ".$start."," .$reclimit;
$search_result = $conn->query($search_sql);
HTML
<body>
<?php
if (isset($search_result->num_rows) > 0) {
?>
<h2 class="result-title">Results matching your need</h2>
<?php
while($search_ok = $search_result->fetch_assoc()) {
$user_id=$search_ok['Id'];
$user_name=$search_ok['Name'];
echo "
<div class='search-section'>
<div class='search-profile'>
<div class='s_user_id'>{$user_id}</div>
<div class='s_user_name'>{$user_name}</div>
</div>
</div>
";
}}
for($i=1;$i<=$tpages;$i++) {
echo "".$i."";
}
?>
</body>
The pagination which you are using is simple and working one. But the pagination which you are searching is smart way and you should achieve this by using some if conditions. Similar answer are there in SO. Go to the following, this may help you
Smart pagination algorithm
PHP pagination
Limit pagination page number
It's a simple idea, but I didn't test it. Edit foreach displaying numbers:
$pgStart = 1;
if (isset($_GET['page'])) { // get first showing number = current page - 2
$pg = $_GET['page'] - 2;
$pgStart = $pg + 5 > $tpages ? $tpages - 4 : $pg; //EDIT fix when reach pages end
$pgStart = $pg < 1 ? 1 : $pg; // This must be after ending correction (previous line)
}
if ($pgStart > 1) { // show 1
echo '1 ... ';
}
for($i = $pgStart; $i <= $tpages && $i < $pgStart + 5; $i++) { // show 5 pages
echo ' '.$i.' ';
}
if ($i < $tpages) { // show last
echo ' ... '.$tpages.'';
}
EDIT
Output of this script with $_GET['page'] = 7 and $tpages = 20 from php sandbox is (without linebreaks):
1 ...
5
6
7
8
9
... 20
Here is my index.php code
My problem is my pagination has a continuous number of
pages.
<?php
$limit = 10;
$offset = (isset($_GET["page"]) ? $_GET["page"] - 1 : 0) * $limit;
$query = "SELECT * FROM employee ORDER BY employee_datecommenced ASC LIMIT
$offset,$limit ";
$list = getdata_inner_join($query);
?>
<?php
$total = $dbcon->query("SELECT count(*) FROM employee") or
die(mysqli_error());
$fetch = $total->fetch_assoc();
for($x = 0; $x < $fetch["count(*)"] / $limit ; $x ++){
$page = $x + 1;
if((isset($_GET["page"]) ? $_GET["page"] : 1) == $page)
$page = "<b>".$page."</b>";
echo ''.$page.' ';
}
?>
Click here to see the output photo
Thanks in advance
You say "My problem is my pagination has a continuous number of pages", but why is that a problem? What do you need to change?
in your for loop while printing the anchor tags, check the current page, if suppose the page is ($current), disable ($current-1), and print $current to ($current+5) and '....' and (current+1), if current is $min or $max manage the prev and next
Im facing some issue on counting total number of output.
<?php
$count = 1;
while ($count <= 10)
{
echo "$count ";
++$count;
}
?>
Result output
1 2 3 4 5 6 7 8 9 10
so what i want is to add all the result that is
1+2+3+4+5+6+7+8+9+10 = ? in my same code?
Try
$count = 1;
$add=0;
while ($count <= 10)
{
$add=$add+$count;
echo "$count ";
++$count;
}
$count = 1;
$countall = 0;
while ($count <= 10)
{
echo "$count ";
$countall=$countall+$count;
$count++;
}
echo "$countall";
try this
Simply use the range function and array_sum to get the result
array_sum(range(1,10))
Evidently not what you are looking for, but if what you need is to calculate a summation, you can use this formula:
Using it you can calculate the result of adding all the values of $count in this code:
<?php
$count = 1;
while ($count <= $n)
{
echo $count.' ';
++$count;
}
?>
That will be:
<?php
$result = $n * ($n + 1) / 2;
?>
Which for $n = 10 is 55.
<?php
$combinedArray = array("apple","banana","watermelon","lemon","orange","mango");
$num_cols = 3;
$i = 0;
foreach ($combinedArray as $r ){
/*** use modulo to check if the row should end ***/
echo $i++%$num_cols==0 ? '<div style="clear:both;"></div>' : '';
/*** output the array item ***/
?>
<div style="float:left; width:33%;">
<?php
echo $r;
?>
</div>
<?php
}
?>
<div style="clear:both;"></div>
The above code will print out the array like this:
apple --- banana --- watermelon
lemon --- orange --- mango
However, I need it like this:
apple --- watermelon --- orange
banana --- lemon --- mango
Do you know how to convert this? Basically, each value in the array needs to be placed underneath the one above, but it must be based on this same structure of 3 columns, and also an equal amount of fruits per column/row (unless there was like 7 fruits there would be 3 in one column and 2 in the other columns.
Sorry I know it's confusing lol
Thanks everyone for your help... I realized a better way to do it though. Simple put, I have 3 columns floating next to eachother. And in each column, I add a list of the items into it and stop when I hit the max items per row.
working code:
<div style="float:left; width:33%;">
<?php
$combinedArraySizeOf = sizeof($combinedArray);
$num_cols = 3;
$iPerRow = $combinedArraySizeOf / $num_cols;
for ($i=0; $i!=$combinedArraySizeOf; $i++){
if ($i % $iPerRow == 0){
echo '</div><div style="float:left; width:33%;">';
}
echo $combinedArray[$i]."<br />";
}
?>
</div>
<div style='clear:both;'></div>
Don't forget to clear both at the end if necessary :P
Why aren't you doing exactly what you want to do? I mean show them in columns, instead of rows?
$combinedArray = array("apple","banana","watermelon","lemon","orange","mango");
$num_cols = 3;
$rowCount = ceil(count($combinedArray)/$num_cols);
$i = 1; // in order the modulus to work correctly
?>
<div style="float: left; width:33%"> <!-- this is the first column -->
foreach ($combinedArray as $r ){
?>
<div> <!-- just a div containing $r -->
<?php
echo $r;
?>
</div>
<?php
// this is where the magic happens
// check if we have enough rows and start another column
if ($i % $rowCount == 0) {
?>
</div> <!-- close the previous column and start a new one -->
<div style="float: left; width:33%"> <!-- this is the new column -->
<?php
}
$i++;
}
?>
</div> <!-- closing the last open column -->
<div style="clear:both;"></div>
This should do just the job you wish. Marvin's answer is better if you want to use only tables without divs.
$combinedArray = array("apple","banana","watermelon","lemon","orange","mango");
$step = 2;
$i = 0;
$new_array = array();
foreach ($combinedArray as $r ){
$remainder = ($i % $step);
$new_array[$remainder][] = $r;
$i++;
}
foreach($new_array as $array)
{
echo implode(' --- ', $array)."<br>";
}
Would this work?
$combinedArray = array("apple","banana","watermelon","lemon","orange","mango");
$num_cols = 3;
$rows = ceil(count($combinedArray)/$num_cols);
for($i = 0; $i < $rows; $i++){
for($j = 0; $j < $num_cols; $j++){
echo $combinedArray[(($i+$j) * $rows)-$i];
}
echo "<br />";
}
This would also need to check that the value existed for cases where the number of items wasn't precisely divisible by the number of columns, you could do that with the following change:
$combinedArray = array("apple","banana","watermelon","lemon","orange","mango");
$num_cols = 3;
$rows = ceil(count($combinedArray)/$num_cols);
for($i = 0; $i < $rows; $i++){
for($j = 0; $j < $num_cols; $j++){
$cell = (($i+$j) * $rows)-$i;
if($cell > count($combinedArray)) break;
echo $combinedArray[$cell];
}
echo "<br />";
}
If this order is what you ideally want, but it's not critical that it works in all browsers, perhaps you should look at coloumn layout (still very experimental css3 draft). If you use dispay inline block for the element in each coloumn you'll have the current order as a fallback.
You could also use a table for the layout and use a for loop something like this (pseudo php code, it's been a while since I've coded any php):
maxHeight = Math.ceil(array.length / 3) // meaning length=6 will give 3,
// length=7 will give 4
$x = -1; // horizontal index
for(i = 0; i < array.length(); i++){
$y = i % maxHeight; // vertical index
if($y == 0){
$x++;
}
addToTable($x,$y, array[i]);
}
I have the following code, which is the basis for pagination in a larger application. However, it does not work, as although I should be obtaining the value of pg from the url, pg never goes higher than 2. For some reason, next = pg+1; seems to always see pg as 1, regardless of what is passed on the url. It is a similar problem with last. I assume I am overriding the value obtained from GET, but I am unsure where.
The problem seems to be in how I am working out $max and the limit, as instead of 0, 10, -10, 10 gets passed. Also the ifcode before $max does not seem to succeed in stopping pg from being 0.
<?php
if (isset($_GET["pg"])) {
$pg = $_GET["pg"];
} else $pg = 1;
$con = mysql_connect("localhost","","");
if(!$con) {
die('Connection failed because of' .mysql_error());
}
mysql_select_db("ebay",$con);
if ($pg < 1) {
$pg = 1;
} elseif ($pg > $last) {
$pg = $last;
}
$table = 'AUCTIONS';
$page_rows = 10;
$max = ' limit ' .($pg - 1) * $page_rows .', ' .$page_rows;
$rows = getRowsByArticleSearch($query, $table, $max);
$rowcount = count($rows);
echo $rowcount;
$last = ceil($rowcount/$page_rows);
$page_rows = 10;
$rowcount = 2;
// Would normally obtain the number of rows returned, but database stuff is snipped for brevity
$last = ceil($rowcount/$page_rows);
if ($pg < 1) {
$pg = 1;
} elseif ($pg > $last) {
$pg = $last;
}
$self = htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'utf-8');
echo " <a href='$self?pg=1'> <<-First</a> ";
$previous = $pg-1;
echo " <a href='$self?pg=$previous'> <-Previous</a> ";
echo "---------------------------";
$next = $pg+1;
echo " <a href='$self?pg=$next'>Next -></a> ";
echo " <a href='$self?pg=$last'>Last ->></a> ";
The code is correct, however, the data is wrong.
When you have
$page_rows = 10;
$rowcount = 2;
it actually means, that you have 2 rows displayed on pages which will display 10 rows each. This makes it 1 page in total.
Change it to
$page_rows = 10;
$rowcount = 200;
and voila, you will get your pagination.
Here's your problem:
$last = ceil($rowcount/$page_rows);
That's setting $last to be 1, and then you have:
if ($pg > $last) {
$pg = $last;
}
Edit: I wonder if you meant this, instead:
$last = ceil($page_rows/$rowcount);
Edit again: as per Cassy's answer, you probably really just need to set the right values for these variables:
$page_rows = 10;
$rowcount = 2;
based on the now revised question:
$rowcount = count($rows);
will naturally always return 10, as you're limiting the result
... LIMIT 10;
But this might help:
SQL CALC FOUND ROWS
Example:
mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name
-> WHERE id > 100 LIMIT 10;
mysql> SELECT FOUND_ROWS();
The first query will still return your articles, while the second will return the number of rows the previous select would have had if not using the LIMIT clause.
Hope that helps.