Link to home
Start Free TrialLog in
Avatar of Sid123
Sid123

asked on

page wise search in php

Hi,
    I want to make a page in which there will be number of pages listed according to items in the database ....like 2 items per page....10 items means five pages need to be shown with links. I have used looping and a difficult method to carry out this. It works but I feel that its not an efficient way...could increase the processing speed though I am not sure. I know that one can use LIMIT (mysql) for this. Also I need to  show like  1,2,3,4,5 Next and in next page Previous 6,7,8,9,10. I havent worked with the LIMIT thing so was seeking out some help.

Sid
Avatar of rstorey2079
rstorey2079

Here's a bit of code that may help you out.  This doesn't get into displaying 1 2 3 4 5  but it will point you in the right direction.  To display all the available pages, you'd have to get the total number of results and then just calculate how many pages there will be and display the links.

<?php

if($_URL['pageID']=="") {
   $pageID = 1;

}

$numItemsPerPage = 5;

$sql = "SELECT * FROM stuff LIMIT " .($pageID*$numItemsPerPage).",".(($pageID+1)*$numItemsPerPage);

//run the sql

//output your results



echo "<a href='myPage.php?pageID=".$pageID+1.'>Next page</a>";

?>
ASKER CERTIFIED SOLUTION
Avatar of ldbkutty
ldbkutty
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
$_URL?
Don't you mean $_REQUEST or $_GET?
Anyhow, you must intval() the page number, you don't want funny things happening with it, right? :)

the query is by the way:

$pageID = (isset($_REQUEST['pageID']) && ((int)$_REQUEST['pageID']>0))?(int)$_REQUEST['pageID']:1;
$recordsPerPage = 10;
$firstRec = ($pageID-1)*$recordsPerPage;

$sql = "SELECT * FROM table ORDER BY id LIMIT {$firstRec}, {$recordsPerPage};";

There isn't a much more efficient way to do it. This sends 1 query and fetches only the relevant records.
You can of course fetch all the DB to a Session, and then only read it from there, but... come on, that's just heavy on the server.
oops, confused with coldfusion there.  I do mean $_GET.