Hello!

hello i'm a newbie learning php scripts, so here's my question i query a data from my database, the list i query was way too long, how can i make the list much more shorter?

I want it to like to show 10 data list and on the next form the other 10 and so on

did i explain it correctly? ( sorry for my bad english )

Thanks!

Recommended Answers

All 2 Replies

Assuming you are using mysql you can limit the result with a LIMIT clause in your select statement.

Hi dudzkie,

It sounds like you're after 'pagination' - where results are displayed over several pages, rather than lumped all together on one.

Try this:

1. Let's assume we have a database with a table called 'tbl_accounts'.
2. We want to find all account holders with the name 'Jack'.
3. Next we want to retrieve the names, then show 10 records per page

/* Set page number */
$page_number = 1; // Or set it from the url by using, $page_number = $_GET['p'];

/* How many results to display per page */ 
$results_per_page = 10;

/* Which page of results are we looking for? */
$first_record = ( ($page_number-1)*$results_per_page );

/* Set value of name to be searched */
$name = "Jack"; 

/* Retreive all matching records */
$sql = "SELECT * FROM tbl_accounts WHERE name = '".$name."'";
$result = mysql_query($sql) or die ('Error, query failed!');

/* Store the number of results */
$total_results = mysql_num_rows($result);

/* No let's get the first page of results */
$sql = "SELECT * FROM tbl_accounts WHERE name = '".$name."' LIMIT $first_record, $results_per_page";
$result = mysql_query($sql) or die ('Error, query failed!');

/* Display results screen */
for( $i=0; $i < mysql_num_rows($result); $i++ ) {
	print_r( mysql_fetch_assoc($result) );
}

/* Calculate how many pages-worth of results are available */
$total_pages = ceil($total_results/$results_per_page);

/* Display page links */
for( $i=1; $i<=$total_pages; $i++ ) {
	echo '<a href="results.php?p ='.$i.'">Page '.$i.'</a>';
}

/* To display page 2, simply reload the code above with '2' as the page variable. */
/* e.g. http://www.my_site.com/results.php?p=2 */
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.