Paging in PHP – PHP Paging Tutorial
PHP Paging & Automatic Pagination Tutorial - Paging made easy
I have written a php paging tutorial before. Admittedly, it wasn't the greatest. I don't think I was as clear as I wanted to be. SO I'm trying again.
At the end of this tutorial, there is a file named php-automatic-pagination.php.txt
Please download it! It will help you understand the following.
Here is what we will be making..nice, simple pagers! (Dont worry about the Image #x text, thats really not part of the tutorial)

Paging in php and automatic pagination is something every coder has to deal with when coding in php. I mean, you COULD show all results on 1 page and skip the php paging, but paging is necessary to reduce bandwidth and organize content. Paging is very easy to do and I will walk you through it step by step.
PHP automatic paging comes with a few questions:
Paging 1 : Page Size - How many results would you like to display per page?
Paging 2 : How can we bring back proper results in mysql?
Paging 3 : How can we print a pager that will help show the next items.
Decide on your page size - 10, 15, 25, 50, 100. It really depends on what you would like to do. For this tutorial I will use 15.
//we want 15 results per page
$pgsize=15;
//if there is a p variable in the query string e.g: page.php?p=5 we will get this value, else we will use 1 (page 1)
$pg=(is_numeric($_GET["p"]) ? $_GET["p"] : 1);
//lets determine where we would like to get results from
//if $pg is 1, this calculation results in 0 (we want to start from the first record in the database)
//if $pg is 2, this calculation will result in 1*15..which means we will start at the 15th index of the database (row 16)
$start=($pg-1)*$pgsize;
//let us query the database for our results
//you will notice LIMIT and $start and $pgsize.
//On page 1, this query will be SELECT * FROM image_table LIMIT 0,15 - this means return 15 rows starting at row-index 0 (row 1)
//On page 2, this query will be SELECT * FROM image_table LIMIT 15, 15 - this means we will return 15 rows starting at row-index 15 (row 16)
//On page 3, this query will be SELECT * FROM image_table LIMIT 30,15 - this means we will return 15 rows starting at row-index 30 (row 31)
GET IT?!?!?!
$imgs=mysql_query("SELECT * FROM image_table LIMIT $start, $pgsize");
//we will also need the total number of records in our table
//notice there is no limit? we want to know how many records are in the entire table!
//we can use COUNT(*), COUNT(1), or COUNT(fieldname), they will all return the same result
$img_total=mysql_query("SELECT COUNT(1) FROM image_table");
//mysql_query returns a resource id, we can use this to get the row it has returned
$img_total=mysql_fetch_row($img_total);
//the count will be the first field in this row
$img_total=$img_total[0];
//lets determine how many pages we will need
//WRONG!, this will cut off results..why?
//say we have 31 images, and our page size is 15. 31/15= ~2.x...We need to round this result up!
$max_pages=$img_total / $pgsize;
//use this line instead
$max_pages=ceil($img_total/$pgsize);
Once we have all this information, we can use a handy little function I have written named printPager. This function will print out a neat little pager. It uses a helper function named add_querystring_var which was from Added Bytes here:
http://www.addedbytes.com/code/querystring-functions/
Copy/paste this function into your page or into one of your includes:
This will print out your awesome little pager!
PHP Automatic Pagination Function
print '<div class="clear"></div>';
print '<ul class="pager">';
$i=1;
if($pg!=1){
$url=$_SERVER["SCRIPT_NAME"];
$url.=add_querystring_var("?".$_SERVER["QUERY_STRING"], "p", $pg-1);
print '<li class="prev"><a href="'.$url.'"><<</a></li>';
}
while($i<=$max_pages){
$url=$_SERVER["SCRIPT_NAME"];
$url.=add_querystring_var("?".$_SERVER["QUERY_STRING"], "p", $i);
if($pg==$i){
print '<li class="current">';
print '<span>'.$i.'</span>';
print "</li>";
}else{
print "<li>";
print '<a href="'.$url.'">'.$i.'</a>';
print "</li>";
}
$i++;
}
if($pg!=$max_pages){
$url=$_SERVER["SCRIPT_NAME"];
$url.=add_querystring_var("?".$_SERVER["QUERY_STRING"], "p", $pg+1);
print '<li class="next"><a href="'.$url.'">>></a>';
}
print '</ul>';
print '<div class="clear"></div>';
}
function add_querystring_var($url, $key, $value) { $url = preg_replace('/(.*)(\?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&'); $url = substr($url, 0, -1); if (strpos($url, '?') === false) { return ($url . '?' . $key . '=' . $value); } else { return ($url . '&' . $key . '=' . $value); } }
Print Pager is called like so:
PHP Pager Styles
/*pagers*/
div.clear{clear:both;}
/spacing between numbers and sizes
ul.pager li {
float:left;
margin-right:5px;
font-size:8pt;
padding: 2px 5px 2px 5px;
}
//link color
ul.pager li a{
color:red;
}
//link hover style
ul.pager li a:hover{
text-decoration:underline;
color:red;
}
//current page styling
ul.pager li.current span{
color:red;
}
//previous and next stylings
ul.pager li.prev, ul.pager li.next{
}
Download this tutorials script! It will help you understand. Right click: php-automatic-pagination-tutorial.php and click Save as. Then get rid of the .txt extension and name it php if you would like to run it. You will need to setup a database table to use for the tutorial. It can have an id field and another field.
If you enjoyed this post please leave a comment! I like reading and responding to all my readers!
Thanks
![]()
Use HostGator 2010 Coupon Code: 994offhgpackage for $9.94 off your first month!
(First month will cost $0.01)
Rounded Corners Using CSS Technique
This is a neat lil trick, that doesnt take to long to do, but makes a site look that much more professional.
It works across browsers, and is used quite often.
It may become obsolete once IE and other browsers decide to support the new set of CSS3 specs. Until then this is a good technique to depend on. If designing for Mozilla based browsers, there is a css property in the making named border-radius.
-moz-border-radius will allow you to set a rounded border on any block object.
This technique however, involves using 4 images and 3 divs.
Here are the images we will be using:
Top Left
Top Right
Bottom Left
Bottom Right
Open up notepad, or notepad++, or whichever editor you use.
Type
<html>
<head>
<title>Rounded Corner Tutorial</title>
</head>
<body>
<body>
<html>
In the head section add:
<style>
body{background-color: #e0e0e0;} //these are zeros not o's
</style>
Save as .html and view it in your browser. You should have a gray page.
Now, between your body tags type this
<div id="roundDiv">
This is the content
</div>
And add this to your style definition
#roundDiv{background-color: white; width: 800px;}
Now, previewing in browser you should see a gray page with a white div containing the words "this is content".
We are going to add a div to roundDiv. Since this is the first item in round div, it starts at the top left corner.
In this top div, we will add the image for the top left corner.
Add this to roundDiv Before "this is content"
<div class="roundTop"><img src="tl.gif" class="corner"/></div>
After this line would come the content.
Add this to roundDiv After "this is content"
This holds your bottom left image
<div class="roundBot"><img src="bl.gif" class="corner"/></div>
Now, between your style tags add this definition
.corner{display: block; width: 16px; height: 16px;} //use your actual values here, for this example our images are 16x16
So far our html page should look like this:
<html>
<head>
<style>
body{background-color: #e0e0e0;}
#roundDiv{width: 800px; background-color: white;}
.corner{display: block; width: 16px; height: 16px;}
</style>
</head>
<body>
<div id="roundDiv">
<div class="roundTop"><img src="tl.gif" class="corner"/></div>
This is content
<div class="roundBot"><img src="bl.gif" class="corner"/></div>
</div>
</body>
</html>
If you preview this in your browser you should see a white div, with rounded corners on the left side.
This in itself is a neat div and you don't have to add the right corners. This effect is good in itself.
To get the rounded corners we really want, we are gonna set a background image on the top and bottom divs.
We will set a background image url, set it to not repeat/tile, and set its position accordingly.
To your style tags add this definition for the top right corner
.roundTop{
background-image: url('tr.gif');
background-repeat: no-repeat;
background-position: top right; // specify to align top, and to the right of the div
}
Now for the bottom right corner
.roundBottom{
background-image: url('br.gif');
background-repeat: no-repeat;
background-position: bottom right; // specify to align bottom, and to the right of the div
}
Your entire html file should look like this:
<html>
<head>
<style>
body{background-color: #e0e0e0;}
#roundDiv{width: 800px; background-color: white;}
.corner{display: block; width: 16px; height: 16px;}
.roundTop{
background-image: url('tr.gif');
background-repeat: no-repeat;
background-position: top right; // specify to align top, and to the right of the div
}
.roundBot{
background-image: url('br.gif');
background-repeat: no-repeat;
background-position: bottom right; // specify to align top, and to the right of the div
}
</style>
</head>
<body>
<div id="roundDiv">
<div class="roundTop"><img src="tl.gif" class="corner"/></div>
This is content
<div class="roundBot"><img src="bl.gif" class="corner"/></div>
</div>
</body>
</html>
This is the result (low-quality pic):

And there you have it, easy rounded corners!
Installing and Configuring MySql/Connecting with C#
Recently, I was asked to do some C# development with MySQL as the backend.
Having C# with SQL Server 2005 development under my belt setting up a connection to a MySQL Server was pretty easy, however, I will walk you through the setup.
Two packages you will need are the MySQL Essentials Installer(this installs the server)
and the MySQL Connecter/.NET Installer(this installs the bridge between MySQL and .NET)
The third package, the GUI tools, is optional, but it is a lot easier to work with. (Think of it as a Management Studio Express, for those of you who have used SQL 2005)
MySQL Essentials Package: http://dev.mysql.com/downloads/mysql/5.1.html#downloads
MySqlConnector/NET: http://www.mysql.com/products/connector/net/
MySQL Gui Tools: http://dev.mysql.com/downloads/gui-tools/5.0.html
Run the Essentials Package first, this package actually contains the server instance.
Follow the prompts, they are pretty much straight forward.
When you receive the prompt about your root password, pick a password.
Next install the MySQL Connector.
Follow the prompts, they are pretty much straight forward as well, and should install pretty quickly.
From here, you can use the command line client located in Start>Program Files>MySql Version>MySql Command Line Client, however, I choose to use the GUI tools instead.
If you have not already, launch the GUI tools installer.
Once this is done, go to Start>Program Files>MySql Version#>MySQL query browser
Click the ... button next to Stored Connection.
Click New Connection.
Fill out the properties
Connection: Name the connection
Username: root
Password: password used during setup
Hostname: localhost
Port: default is 3306
Schema: specify the default database, you can leave this blank.
Click apply and close.
In the connection screen, from the dropdown, pick the connection we just created.
Type your password.
If given a warning about a default schema, type test or default in the Default Schema field, this will create
a database named test or default. You can always delete this dummy database afterwards.
To create tables right click your database in the Schemata and click Create New Table.
Most of the GUI is intuitive and should be picked up quite easy.
Connecting to MySQL using C#
Start a C# Application project (I'm using a Console App in my example)
Right click your project and click Add Reference.
Navigate to the Connector DLL.
By default this dll is located at C:/Program Files/MySql/MySql Connector .NET Version#/Binaries/.NET 2.0/MySql.Data.dll
Once this is added add the line:
using MySql.Data.MySqlClient;
using System.Data; //for the ConnectionState enum
to the top of your code.
Add this code to your main/load method:
//sets up the connection string
string connString = "Server = localhost; Database = databaseName; Uid = root; Pwd = pass;";
//creates a new MySqlConnection object
MySqlConnection conn = new MySqlConnection(connString);
try{
//try to open the connection, catch any exceptions
conn.Open();
//if the connection succeeds, print a msg
Console.WriteLine("Connection Succeeded");
}catch(Exception ex){
//print that the connection failed, and the associated Message
Console.WriteLine("Connection Failed: "+ex.Message);
}finally{
//if the connection is currently open, close it
if(conn.State==ConnectionState.Open)
conn.Close();
}
Troubleshooting:
- If you are having trouble connecting, check your username and password.
- Double check the connection string.
- If you are sure the above is correct, make sure the MySql server instance is running. You can do this by
- going to Start>Run. Type services.msc and hit Ok. Scroll down the list to MySql, it should say started. If it does not, right click and hit Start.
- Try to connect with the MySql GUI tools.
Just about everything you can do with SQL Server you can do with MySql using the familiarly named classes:
MySqlConnection, MySqlCommand, MySqlDataReader
Hope this gets you started on using MySql and C#.
Any questions or comments, feel free to ask.
Programming
Today is grad day, last day of school, and out of all the technologies I've learned in the 3 years I've been in college, PHP was my favorite.ASP.NET, JSP/Servlets just seem to bulky. PHP was so lightweight, easy to understand and extremely simple. It's open source model was nice to see to, everywhere on the net there was reusable code and components WITH NO RESTRICTIONS.
At the moment my job is an ASP.NET job, however, I have a big PHP job lined up in a couple months.
We redeveloped an existing system and came in 1st in a competition against 7 other teams! So, we're being brought onto the project.
What are your thoughts on the different development languages?
ASP.NET, JSP with servlets, PHP...which do you prefer and why?