Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
KnowledgeWoods Consulting
5,607 PointsHow to do pagination of table which is fetched from MS SQL ?
I have a table which shows rows as stored in database. How can i paginate it. I am using MS SQL database
2 Answers
Hugo Paz
15,622 PointsI will show you what i usually do, others might have better solutions.
First we save the results from the query on a variable:
$results = your_query_function(arg);
Then we count the number of results:
$number_of_results = count($results);
Then we need to decide how many results per page so we can know how many pages are needed:
//in this case i choose 10 results per page
$pages = ceil($number_of_results / 10);
Now here is the tricky part, you need to know in which page you are so you can get the correct results displayed, page 1 will show 1 to 10, page 2 11 to 20 and so forth.
What i do is to have a variable with the page number, usually through a get. Like this:
//keep im mind that this should be better sanitized
$page = htmlspecialchars($_GET['page']);
So now we know the page we are in, time to get the correct results:
//Set the starting point where we are going to slice the array
$start = $page * 10;
//starting point of the array according to page
$results_to_display = array_slice($number_of_results, $start, 10);
So now we have the correct results in the correct page so you just need to do a loop to display them
At the end we need to create the pagination, i do a for loop:
for($i=0;$i<$pages;$i++){
echo '<li class="yourCoolClass"><a href="'yoururl?page=' . $i . '">' . ($i+1). '</a></li>';
}
KnowledgeWoods Consulting
5,607 PointsThanks a ton....It worked....!!!!!
KnowledgeWoods Consulting
5,607 PointsKnowledgeWoods Consulting
5,607 PointsThanks for the reply. Can you please tell me what is the SQL statement for MS SQL for doing LIMIT. I guess LIMIT 10, 20 only works in mysql
Ryan Duchene
Courses Plus Student 46,022 PointsRyan Duchene
Courses Plus Student 46,022 PointsWill this Stack post do the trick?