How to display long while/for loop in pagination? - php

I have a while/for loop with thousands results. Since it contains several fields, I use table to display it. However, with thousands results being displayed at the same time, it will definitely slow down the performance. How can I display it in pagination?
<table>
<?php $count = 1000;
for($a=1;$a<=$count;$a++) { ?>
<tr>
<td><?php echo $a; ?></td>
<td>This is number <?php echo $a; ?></td>
</tr>
<?php $i++;
} ?>
</table>

My only solution without having a DB with the data would be to pass the array key you are on to the next page. For example:
$start = 1;
$end = 1000;
if(isset($_GET['record_number'])){
$start = $_GET['record_number'];
$end = $_GET['record_number'] + 1000;
}
for($a=$start; $a<=$end; $a++){
//code here
}
Other than that, you might consider creating a list of files in a DB engine so you can use the LIMIT parameter.

If the data comes from a database you can limit the result set. If you are using MySQL you use the LIMIT clause. This will allow you to only fetch the specified number of rows.
SELECT title, description FROM posts LIMIT 25
This will only fetch 25 rows. Then if you want to fetch the results after row 25 you can provide an offset. This is done a little different since the offset comes first in the LIMIT clause. Only one argument is provided MySQL assumes its the limit instead. To select the next 50 rows you use.
SELECT title, description FROM posts LIMIT 25, 50
This can be useful to reduce the result set fetched and help increase performance/load times due to a smaller amount of data that needs to be processed.
I hope this can help you, happy coding!
Update
This is a little tutorial in using the LIMIT clause in MySQL

Here is my example, it's similar to the answer from #AnotherGuy
<form method="GET">
<input type="text" name="rowsPerPage">
<?php
for($i = 1; $i+1 < $count/$rowsPerPage; $i++){
echo '<input type="submit" name="page" value="'.$i.'">';
}
?>
</form>
<?php
$begin = (int)$_GET['rowsPerPage']*$_GET['page'];
$take = (int)$_GET['rowsPerPage'];
$sql = "SELECT ... LIMIT {$begin}, {$take}";
?>
It's possible that the code contains "typos", but I hope it will give you new ideas.
I would recommend you to use GET instead of POST. GET will be saved in the URL, in this way, it will be easier to reload the page without losing the page-settings.
www.example.com?rowsPerPage=150&page=2

Related

limited number of rows in a page

Hi I'm retrieving my data from DB
my data is (pic & name ) when I retrieved them I put them in 4 columns
now I wanna limit the number of rows in each page , I want each page shows three rows only
and if there is more data I want to make it display in next page
my code :
<?php
$items_in_row = 4 ;
$index = 0 ;
?>
<table>
<tr>
<?php
while ($row = mysql_fetch_array( $result , MYSQL_ASSOC)){
$index++ ; ?>
<td>
<p>
<img id='g1' src='/<?php echo $row["img"] ;?>' width=130 height=130 onClick='f1()'>
</p>
<p> Name: <?php echo $row['name'] ; ?> </p>
<br>
</td>
<?php if ($index%$items_in_row == 0){ ?>
</tr>
<tr>
<?php }
} ?>
</tr>
</table>
One way to do this is to use the LIMIT() function in SQL, passing in variables that you are storing in the session in PHP. Let's say you want 3 rows of 4 pictures on each page, then you want 12 pictures. So you do something like
select * from pictures LIMIT(0,12)
This returns the first 12 items.
You can do it by just tracking page number. Maybe you have a $page variable in your PHP. If you are on page 2, $page contains 2. Use that to construct a dynamic SQL query with your PHP maybe like this...
$sqlQueryStatement = "select * from pictures LIMIT(". ($page-1)*12 . ", 12)";
What this does is for page 2, it produces the sql statement:
select * from pictures LIMIT(12,12)
See how that works? Now you execute that SQL, and you have the set of results that should be output for page 2.
You can use some further logic to take these basic concepts and run with them...extending them to uses like creating the clickable pagination numbers on the bottom of your results and so forth.
i develop my pagination jobs using the following algorithm:
...1) selecting the results
$page = 1; // what page to show, if you dont know 1 is default.
$maxthingsperpage = 5; // how many things (etc. what you show) per page
$offset = ($page * $maxthingsperpage) - $maxthingsperpage; // db id to start reading
$result = mysql_query("SELECT * FROM things LIMIT ".$offset.",".$maxthingsperpage);
...2) display the things into page
$numrows = mysql_num_rows($result);
$numthingstodisplay = ($numrows > $maxthingsperpage ? $maxthingsperpage : $numrows);
while ($row = mysql_fetch_array( $result , MYSQL_ASSOC)) {
... display here without worrying about when to break; num rows are exact
}
you can replace $maxthingsperpage with your $items_in_row

How to Limit the lines my Php List is showing

I have a submit form that displays into a list format and I'm wondering what I can do to make it so that the list only displays a certain number of the most current submitted info. I'm testing it and currently the list is on a page and just displays 50+ submissions stretching out the page very long.
<?php
$query='select * from article order by `article`.`time` DESC';
$result=mysql_query($query);
echo '<table width="600px">';
while($row = mysql_fetch_array($result))
{
echo "<td><a href='".$row['url']."'>".$row['title']."</a></td> <td>".$row['description']."</td><td>".$row['type']."</td></tr>";
}
echo '<table>';
?>
Welcome to SO! Modify your sql statement as follows:
$query='SELECT * FROM article ORDER BY `article`.`time` DESC LIMIT 10';
Change 10 to however many entries should be displayed.
Even though you only should select the data you need, you might want to take a look at a for-loop, which is useful if you know how many times you want to run something. You might end up with a loop which looks like this:
for($i = 0; $i < 10 && $row = mysql_fetch_array($result); $i++) {
echo "<td><a href='".$row['url']."'>".$row['title']."</a></td> <td>".$row['description']."</td><td>".$row['type']."</td></tr>";
}
This code runs 10 times IF you have enough data.

bad planing with mysql_fetch_assoc?

I am making a page where people can make posts. All of those posts are then shown in a table of 24 cells. I can have the last 24 posts shown with no problem, but now I don't know how to show the prior group(s) of posts. How can I fix my code to do that? I actually have this:
(I'm removing lines to make it easy to read)
$sql = "SELECT
topics.topic_id,
topics.topic_subject
ORDER BY
topics.topic_id DESC";
// ---check everything is fine---- //
function retrieve_info($result)
{
if($row = mysql_fetch_assoc($result))
{echo $topic_if; echo $topic_subject; //and what I want in every cell
}
}
<table width="100%" height="751" >
<tr><td><?php retrieve_info($result);?></td>
<td><?php retrieve_info($result);?></td>
<td><?php retrieve_info($result);?></td>
<td><?php retrieve_info($result);?></td></tr>
<!-- repeat a few more times :-) -->
</table>
I though that by changing the variable $row with a number before the if statement would alter the output, but I still see the same data printed on screen. What should I do to be able to show next group of posts?
Thanks!!!
At some point when you have hundreds or thousands of records, you are going to want to paginate the results and not just select all records from the table.
To do this you will run one query per 24 records, your sql would be more like this:
$sql = "SELECT
topics.topic_id,
topics.topic_subject
ORDER BY
topics.topic_id DESC
LIMIT 0, 24
";
and for the next 24,
LIMIT 24, 24
then
LIMIT 48, 24
and so on.
You would then make next/previous buttons to click which would refresh the page and dispay the next 24, or you would get the next results with an AJAX request and append the next 24 through the DOM.
This suggests having to take a slightly different approach then calling the same function from each table cell.
More like get the relevant 24 results based on the page number you are on, then loop through the results array and print out the table code with values inside it. Based on if the iterator of the loop is divisible by 4 (looks like your grid is 4x6), you print out new tags for the new row, and that sort of thing.
Search around a bit for pagination in php and mysql to get a sense of how this all fits together.
function retrieve_info($result)
{
while($row = mysql_fetch_assoc($result))
{
$topic_id = htmlspecialchars($row['topic_id']);
$topic_subject = htmlspecialchars($row['topic_subject']);
echo '<td>';
echo $topic_if;
echo $topic_subject; //and what I want in every cell
echo '</td>';
}
}

Generate html table with variable rows and cells

I am trying to generate a table that takes data from a mysql database. There are 8 columns but the number of rows is variable depending on the amount of info from the database. The problem I'm running into is that I have two things that are variable and I don't know how to use two while loops (or if that's the right choice).
The code below can generate a table with 8 columns and a variable amount of rows but I don't know how to replace thing with sequential integers. I would like each cell to have just one integer in it sequentially like a while loop until the numbers = $end.
CODE:
<?php
$end=82; //will get all this data from a dabase
$rows=ceil($end/8);
$x=0;
$start=0;
?>
<table>
<?php
While ($x<=$rows){
echo"
<tr>
<td>
thing
</td>
<td>
thing
</td>
<td>
thing
</td>
<td>
thing
</td>
<td>
thing
</td>
<td>
thing
</td>
<td>
thing
</td>
<td>
thing
</td>
</tr>
";
$x++;
}
?>
</table>
This will output eight numbers per row starting at 1 and going to $end. I am unsure of what $maxprobs is here.
<?php
$end=82; //will get all this data from a dabase
$rows=ceil($end/8);
$x=0;
$start=0;
?>
<table>
<?php
while($x<=$rows) {
echo "<tr>";
for ($y = 0; $y < 8; $y++, $start++) {
if ($start <= $end) echo "<td>$start</td>";
}
echo "</tr>";
$x++;
}
?>
</table>
I have to ask - if you're pulling rows from a MySQL database, and you want your table to have a dynamic number of rows depending on the data, is there any specific reason you're not doing it the regular way, with a while loop and a mysql_fetch function?
$data = mysql_query("SELECT row1, row2, ... , row8 FROM table WHERE ...); // Sample query, edited for brevity.
echo "<table>";
while ($result = mysql_fetch_object($data))
(
echo "<tr>";
echo "<td>".$data->row1."</td>;
echo "<td>".$data->row2."</td>;
... // Edited for brevity. Include as many columns as you queried.
echo "<td>".$data->row8."</td>;
echo "</tr>";
}
echo "<table>";
Unless you have a really specific reason not to do it this way, I'd use this method. It's flexible and it will print as many rows as your query returns (meaning that you only need to change your query, not your code).
Additional information on mysql_fetch_object and mysql_query can be found here and here, respectively.
Take a look at the php website, nearly all their entries have examples, the database stuff shows a while loop, this is the best way to do it..
write the table opening tag, plus any headers..
while able to get more database data, get it, and do
display the table row open tag
display the row, by looping through the fields, and outputting them between cell tags
dispaly the end of row tag
now you've finished with your data, write the end of the table
There are a lot of examples about.
for the looping through the field, thats why they invented a "foreach" , eg wether you have 0, or 10000, you can go through each one, even if its not consecutive, so for each "fruit" in apple, pear, bannana..

Order by date in mysql

I want to sort my result form mysql by date. I use the query like this:
<?php
$date = $db->get_query("select distinct created_date from comments");
$condate = '';
for($i=0; $i < count($date); $i++)
{
$condate = $date[$i]['created_date'];
$data = $db->get_query("select id,created_date from comments where created_date='$condate' order by created_date");
?>
<table border='1' style="float: left; margin-left: 5px;">
<?php
for($j=0; $j<count($data); $j++)
{
echo '<tr><td>';
echo $data[$j]['id'] ;
echo '</td><td>';
echo $data[$j]['created_date'];
echo '</td></tr>';
}
?>
</table>
<?php
}
?>
This query produce result like this:
2009-07-10
2009-07-10
2009-08-21
2009-07-29
2009-08-15
The result is not sorted.
I want to see the result is:
2009-07-10
2009-07-10
2009-07-29
2009-08-15
2009-08-29
with separated table order by created-date.
I want to know sorting date in mysql result .In this case $condate is variable for validate condition.The value of $condate is all created_date in comments table. I produce this as within loop and set the value is.
Please help me!
If you're only selecting results from a single date, then there's nothing to sort by. What exactly is the WHERE condition doing?
Edit: Now that you've posted your code, I can offer a suggestion. Your original code is running a separate query for each different date. What you really want is a single query that returns the results for all dates, but in a specific order, which is what the query in the code below does. Try this instead:
<?php
$data = $db->get_query("select id,created_date from comments order by created_date");
?>
<table border='1' style="float: left; margin-left: 5px;">
<?php
for($j=0; $j<count($data); $j++)
{
echo '<tr><td>';
echo $data[$j]['id'] ;
echo '</td><td>';
echo $data[$j]['created_date'];
echo '</td></tr>';
}
?>
</table>
Note that you already had all of this in your original code! You just managed to convince yourself that the task was more complicated than it actually was. :)
Because you put = in the where clause, so all the records will be in the same day and the sort will not be useful.
Edit
Are you using date field type for created_date field or string? if it's string so that may cause your problem...
Maybe you have your date field is stored as a "string" and not something like datetime?
If you check with:
describe table_name;
How is your date stored?
You are looping through results that aren't ordered to generate the dates you are asking for in the second query. Up near the top you were querying:
$date = $db->get_query("select distinct created_date from comments");
// should be (and excuse the keyword capitalization, I just think its easier to read)
$date = $db->get_query("SELECT DISTINCT created_date FROM comments ORDER BY created_date");
You just put your ORDER BY clause on the wrong query.
I dont think you need to execute 2 queries.
Try executing
$data = $db->get_query("select DISTINCT id,created_date from comments where created_date='$condate' order by created_date");
I think you had all built-in in your code but you just got confused a little.
Do let me know whether this solved your problem or not.

Categories