Okay, today I'll explain a little bit about pagination. Firstly, what do i mean by pagination?
What is pagination?
You see pagination everyday when you use
http://www.google.com, at the very bottom of the page, you will see a list of pages, all of which have the next set of records for your particular search.
Whats the point?
Well the most blatently obvious
point is that you are able to deliver results to your users in chunks that are far easier to digest, and look much prettier =D
Okay, enough chit-chat.. tell me how to do it!
Okay, lets start with a simple query.
| PHP Code |
<?php
$sql = "SELECT * FROM `logs`";
?>
|
If you are not familiar with
SQL, then go learn!
Now chances are that the above SQL statment will return far more than 1 result. So lets firstly output all of the records that we find.
This is how to loop through all of the records that you get..
| PHP Code |
<?php
//connect to the database
$connect = mysql_connect("server","username","password");
mysql_select_db("dbname");
$sql = "SELECT * FROM `logs`";
$query = mysql_query($sql,$connect);
if(mysql_num_rows() > 0)
{
while($record = mysql_fetch_assoc($query))
{
echo $record["ip_addr"];
}
}
else
{
echo "There were no records found!";
}
?>
|
Okay, so as you see, that will loop through all of the results, and then give me the value of the column "ip_addr", and echo it out to the browser. To get at different columns within the database, you will just need to change the key of the array, ie to get at the column "log_id", you will write $record['log_id'], its
not hard to understand =D
Now that we have all of the records sorted out fine, how do we add pagination to the results? This involves editing the SQL. If I type it out first, and then explain later.. it might be better.
| PHP Code |
<?php
//first we need to decide how much to display per page
$limit = 10;
if(!isset($_GET['page']))
{
$page = 1
}
else
{
$page = $_GET['page'];
}
//start and end records
$start = ($page - 1) * $limit;
$sql = "SELECT * FROM `logs` LIMIT $start, $limit";
?>
|
The LIMIT part of the SQL statement tells the MySQL server which records you want. Remember that the first record is record 0, and the second is record 1, etc.. so the above conditional will sort out the correct page, according to the page number given, and the number of records that you want to be displayed per page =D
For the limit statment, you need to tell MySQL your starting record, and then the amount of records that you would like to display.
You can use the $sql then to tie into your mysql_fetch_assoc() function, and then you can have PAGES OF RECORDS!