Monthly Archives: June 2013

Interactive PHP Applications Using JQuery.AJAX and MySQL

Using AJAX can be tricky and frustrating do to common pitfalls and misunderstandings about how it should be implemented. If this is your first experience with it then I hope you will find this post beneficial and I also hope that I provided adequate enough example and explanation that you won’t have to go on an epic Google search to accomplish what you are trying to do.

For this post I am going to jump right into an example. This example is a small  application that will demonstrate how a web page can exchange information with a MySQL database using JQuery, AJAX and a PHP API.  At a high level this application can be described by the following synopsis.

Build a single web page where I can interactively do the following:

1. Select a userid from a drop down list and dynamically view information about that user without refreshing the client page.
2. Add a new user and update the select list without refreshing the client page
3. Delete a user

Considering the synopsis above, this application will effectively demonstrate how to do the following:

  • Use JQuery.ajax to fetch data from a table in a MySQL database and dynamically load a drop down select list with userids when the page initially loads.
  • Use JQuery.ajax to dynamically submit a form by converting the form data to a serialized JSON object, post this data to a PHP API which decodes the JSON data and facilitates the insert into the MySQL database then sends a response to the client web page and dynamically updates the drop down select list without refreshing the client web page.
  • Use JQuery.ajax to make a call to fetch a database record and dynamically populate an HTML table when the value of a select list is changed by the user, without refreshing the whole client web page.
  • Use a hyperlink to send a delete command to the PHP API which will delete the selected user record from the database and refresh the client.

In this scenario, PHP takes a “behind the scenes” position to handle the data processing. The  front end will be a a simple HTML page that uses JQuery and AJAX to facilitate any actions initiated by the user and CSS for its presentation.


Source Files Include:

  • db.sql
  • mysql_api.php
  • client.php
  • initialize.js
  • interact.js
  • presentation.css

Let’s start by creating a database called “test” and a table called “users” and insert an initial record to get us started. As I did in my book, I’m using MySQL Workbench 5.2 CE as my database console (I provided detailed instruction in my book on how to download and set this up along with a full LAMP stack).  After you set up a connection to your localhost or wherever, simply open the db.sql file in the SQL Editor and execute (by clicking the yellow lightening bolt on the menu bar).


Your database is now set up and contains a couple of records.

For this example I’m using my old Windows 7  Pro machine and I’m running this application out of my C:\Program Files\Zend\Apache2\htdocs folder. When you extract the source code files please put them in the root directory of whatever web server you are using.

Let’s move on to the client.php file. This is the only file that the user will interact with in this sample app. For the purpose of discussion throughout this tutorial, I put divided the Javascript up into two different files and I put all of my CSS presentation code in presentation.css. I simply pull these three files into my HTML file by including them where I want them.








Prevent Hacking from Malicious SQL Injections by Parameterizing SQL Queries

Malicious SQL Injection is a tactic used by hackers to try to insert “control characters” into queries issued over the Internet in an attempt to gain control over the database and issue commands to it. Using parameterization syntax can prevent hacker injection attacks on valuable web sites or other databases.

To use the parameterized query, you need to use MySQLi rather than the MySQL functions. For example:

Parameterized SQL Query Using MySQLi

The key function that facilitates the parameterization of your SQL statment is mysqli::prepare.

PDO is another option for parameterizing your queries to make them secure. Using PDO, the MySQLi example above can be re-written as:

Parameterized SQL Query Using PDO

A less elegant approach to hack proofing your SQL statements is to use the mysql_real_escape_string function to remove unwanted characters from your input variables:

MySQL Escape String Function

Factory Method Pattern

The purpose of the Factory Method Design Pattern is to create objects without the general factory class having to know the exact class names. In this way a general factory can be used to create concrete factories which in turn create specific products.

The Factory Method pattern separates the creator classes from the products they are designed to generate and thus encapsulate the creation of objects (products) which can be useful if the creation process is complex like when it depends on user input or settings in a configuration file, etc.

For example, I will create a general class that has a single static method which will be the factory method for this example:

Factory Method Pattern Ex 1

Take special note to how the factory method returns a new object which is specified by the $type input.

In the next example the factory method will be defined as public and called directly by the client code. I will use interface implementations instead of subclasses. Either way is an acceptable technique in order to achieve the pattern:

Factory Method Pattern ex 2

PHP Namespaces

The PHP namespace is essentially a container that you can keep all of your classes and functions in as a way of preventing name collisions with other classes and methods that have the same name as those in your namespace. Large applications often have hundreds or thousands of components, which lead to a large number of name-clashes. Namespaces allow you to elegantly group components and avoid this problem all the while allowing you to maintain simplicity in your naming conventions instead of having to keep up with complex naming conventions.

You can think of a namespace as being kind of like a directory on a file system. Say you’re running Windows and you have the following two directories on your C: drive, C://DIR_A and C://DIR_B. Now say you have two different text files with the same name, test.txt. Both of these text files can’t exist in the same directory but they can co-exist if you put one in C://DIR_A/test.txt and the other in C://DIR_B/test.txt. Namespaces work in a similar way in that you can have multiple functions, classes and methods with the same names all in the same application or file if they are located in different namespaces.

A namespace is defined with the namespace keyword and a name. It must be declared before any other code, with the exception of rarely used declare statements. Once defined, the scope of the namespace applies to the entire file.


Multiple namespaces may be defined in a single file by using the namespace keyword multiple times. In such instances, the scope of the preceding namespace ends once the next namespace definition appears.

Multiple Namespaces

PHP Callbacks

A callback is a function that is passed to another segment of code, service or process in order for that segment of code, service or process to call the function at some later point in time when a certain condition has been met. A typical use for a callback is handling information that is requested from a web service like the Google Custom Search API.

A callback function is passed by its name as a string using the call_user_func() helper function. Object methods and static class methods can also be called back using call_user_func().

I will go ahead and give some examples of each of these three ways to call a callback by creating a simple function and a class that has both a static method and a normal method (that must be called by an instantiated object).


These first three examples were to demonstrate the three main ways that call_user_func() can be used to pass callbacks. I will continue on with another example to demonstrate a more practical use for callbacks, using them to process data from the Google API.


You can imagine all the other practical uses for callbacks from writing a payment confirmation to your database after a customer makes a successful purchase from your web site’s payment gateway, or writing search results to your database as is implied in the example above.

Lamda Functions

Lambda functions or “anonymous functions,” as they are often referred to, are simply throwaway functions that can be defined at any time and are typically bound to a variable. The functions themselves only exist in the scope of the variable of which they are defined, so when that variable goes out of scope, so does the function.


$double = function($num) { return $num * 2; }

Lambda functions are useful for a number of instances, most notably for many PHP functions that accept a callback function. One such function is array_map(), which allows us to walk through an array and apply a callback function to each element of the array.

PHP Closures

Closures are anonymous functions and are like lambda functions, but smarter in the sense that they have the ability to interact with variables from the outside environment of where the closure is defined. They are functions created without a name, and they are generally passes and callback handlers to other functions.

Added in PHP 5.3, these functions are typically created on the fly, and as such didn’t have access to objects outside of what were being passes arguments to the function. PHP 5.4 adds the ability to access the this scope and therefore the scope of the parent PHP document class.

I’ll demonstrate with a simple example. I’ll create a file called closers.php and create a new class in it called Event. This class is going to have a private property called $name, I’ll just set it my name.

Next I will create a function, and this function is going to return an instance of a function.


class Event
private $name = "Michelle";

public function getFunction ()
return function () { return $this->name; };


$event = new Event();
$func = $event->getFunction();

echo "Hello, ", $func();


Now, with PHP 5.4, this function is going to actually be able to access the $this scope. You may wonder why would I would create a function that returns a function? I do this because the benefit of passing functions around like variables allows us to essentially
encapsulate logic that can be called at a later time in code execution.

A good reason to do this is when you want something to happen after another event occurs.

For example, if I call a web service and I want to call another function to process the results when they comeback, this is a good way to do it. You can create your own special events.

They take functions and arguments and use them to call them at appropriate times at runtime. So what I can do is in my function I simply return, and then now that I have access to the $this scope I can just output what’s in the name property.

So that’s my event class. Now to use it I can create a new instance.

$event = new Event();

I can then call on that function to set a variable equal to that function object, which I can call at a later time.

$func = $event->getFunction();

So because func is now that function, I can now output the result by calling it. So what I should see when I run this is Hello Michelle, and it does this by calling the function that I returned in my class.

So closures, or anonymous functions, were a new addition in PHP 5.3. However, there is internal disagreement among PHP developers as to what the PHP $this scope should refer to exactly. Because of that, it didn’t allow access to it.

Now in 5.4, the PHP $this scope has been allowed, and you can use it to reference instance functions and properties as in the example above.


The concept behind pagination. Let’s say that we have 1,000 photographs in our
database. We probably don’t want to see that entire list of all 1,000
photographs at once. Instead you would only want to return a subset of the list
to the user, a single page of results, and the first page of results might just
have ten photographs on it, and then it would have a link to the next page.
Then that page might have another ten photographs and a link to both the next
page and also back to the previous page. Or you might have a list of all page
numbers at the bottom with links that will allow you to skip around between
pages, so you can go directly from page one to page seven.
If you have a lot of results, you probably also want to communicate with the
user as to what subset of results they are looking at. For example, saying page
one of seven or photographs one through ten out of 1,000. Well,
that’s all pagination.
Whether you realize it or not, you probably are very familiar with pagination
already. Google gives a great example of it. I have searched for PHP on Google
and I came up with a lot of results. In fact, 10 million results. You will see
it gives me the kind of information that says, hey, you are looking at results
one through ten out of about 100,000. So that is the kind of pagination
information that tells us what subset we’re looking for and how many total
records there are.
If we look at the bottom, we’ll see the pages and we can jump to page 7 of the
results or we can simply go to the next page. Going to the next page then will
load another page of results, 11 through 20, and if we go down to the bottom,
we’ll see we now have a previous link as well as the forward link.

Any paginated web page is going to require two sets of information: the subset
of records that are on the current page, and then information about the
complete set of records. That’s what we saw at the top of that Google page.
What records are we seeing and how many records are there total. Of course, the
subset of records on the current page is also going to be used to build the page.
That’s how we’re going to see the results.
The information about the complete set of records is not only going to give us
the information at the top but it’s also going to let us know whether or not
there are other pages that we could jump to. That’s how we get those numbers at
the bottom telling us, hey, you can jump straight to page 7, without it how
else would we know if there is a page 7 or not.
Now, to generate these two sets of information, we’re going to need to keep
track of three things in our code: the current page that we’re on, how many
records should be on each page, and the total number of records that are
available. If we have those three pieces of information, we’ll be able to
calculate everything else we need to know.
In order to make the calculations we need and to pull back the right records
from the database, we’re going to need to make use of MySQL’s syntax, specifically Limit, Offset, and Count.

Now, Limit is going to be the maximum number of records that should be returned
by the query. So for example, if we have a SQL query that has a limit of 20,
then it will return 20 records even if there is 10,000. This corresponds to per
page when we’re doing pagination. It’s how many records do we want to have
returned in that subset of information for a page.
So if we’re looking at a page and we want to have 20 results, we’ll limit it to
20. I think that’s fairly straightforward.
Offset though is a little more complicated. Offset is going to be the records
that should be skipped before SQL starts returning records to us. The reason
why we need an offset is so that we don’t always get the same records over and
over again. If we have limit 20, it will only give us 20 records, but we don’t
always want the first 20 records, sometimes we want the second 20 records. We
want to skip over the first 20 and then start with record 21 through 40. That’s
what offset allows us to do.
The way we can determine offset is by a calculation. We take per page times the
current page that we’re one, minus 1, and that will tell us what the offset
ought to be. If the reasoning behind that math isn’t totally clear to you,
Say for example that we have per page equals to 10, so it will be ten items per page.
Once again our calculation for offset is per page, which is ten, times
the current page, minus 1. If the current page is 1, that calculation works out
so that offset is 0, and that would mean that records 1 through 10 would be
returned to us. If we’re on page 2 though, the offset would calculate out to be
10, and that would mean that records 11 through 20 would be returned to us,
because it would skip the first ten records, it would offset by those ten. That
makes sense. We can see then, as we look down the column of records, how we get
each page of records ten at a time.
So the SQL syntax that we’re going to use to do that in the select statement is
going to be,

SELECT all FROM photographs, LIMIT,and then whatever variable
we have for how many per page, and then OFFSET, which will be whatever offset we want to use.
Now, Count is pretty straightforward. We just want to get a count of how many
records are in the database. The SQL syntax that we’re going to use for that is
simply going to be, SELECT COUNT, and then parenthesis around the asterisk.
That’s the asterisk that we were using here in this statement. It’s to say get
all fields. We’re going to put count around that, so we’re going to say select
all, count everything that comes back from photographs, and that will provide
us with a count. It will tell us how many entries there are in the photographs table.
In the next movie, let’s go back to PHP and see how we can find the pagination
variables we’re going to need so that we can execute these SQL statements.

Now that we have talked about the concepts behind pagination and the MySQL that
we’ll need to use, the next step is to go into PHP and actually find the
pagination variables that we’re going to need to keep track of.
You remember earlier that we said we’ll be keeping track of three variables:
the current page, how many records are on each page, and the total number of
So where we’ll start out adding this is in the public area, public.index.php.
Now, right now I only have two photographs uploaded, you might have more than that.
You certainly can go ahead and put more in there. But the idea is that as
these keep going, they are going just keep growing and growing and growing
until we finally have filled up the page with, let’s say, hundreds of
photographs, and instead I want to limit it to a certain number per page.
So let’s go to index.php and let’s do our pagination here. So right now what
we’re doing is we’re finding all photos. We’ll just go right up above that and
let’s figure out our pagination variables.
So the first thing that we want to figure out is the current page number. What
I have in mind is that each time a page is clicked to go from page 1 to page 2,
we’ll simply send something in the URL string like page=2. Right now that does
nothing, but that would eventually then hopefully take us to a second page.
The way we can do that is by setting page = GET page, and we’ll do a check if
it’s empty, then we’ll set it to 1, because we’re one page 1. If there was no
page specified, go with page 1.
So I have just got a little bit of extra code in there to make sure that it
gets set to some default value, but otherwise I’m going to set it = page, and
I’m making sure that it’s typed as an integer, not as a string.
The second thing is the records per page. Well, that’s really up to us, it’s a
matter of personal taste, you can make it 20 records, you can make it 5
records, it’s how many photographs you want on each page. For now, I’m going to
set this to a very low number, and I recommend you do the same thing, and that
way we don’t have to upload a lot of photographs in order to activate our
paginations. So pick a number like 2, 3, 4, something like that, so that
we’ll be sure of being able to get a second page as soon as we have four photographs.
The last thing is the total record count, how can we go about getting that
total record count. We talked about doing the select count from photographs.
We saw the SQL that makes possible. It tells us how to do it, but we’re trying
to work in an object oriented way here. So the best thing is going to be if we
actually write a new method on photograph that will count all of its records,
and then we can always just ask, hey photograph table, how many records do you have,
and we could do that for all of our tables, all of our classes.
We’ll make it part of our common database methods.
So we’ll need to write that count_all method. Let’s just hide this for a second
and let’s put index over here and open up photograph.php. It’s going to be one
of our common database methods, let’s put it right below find_by_sql, public
static function count_all. So that’s going to be the function that we’re going to use.
Now, we know from experience that we’re going to need to bring in the database
from the global scope, and we know what the SQL is going to look like.
We’re just going to do SELECT count_all FROM, and then the table name, and we can
call that statically too. That’s the same kind of thing we were doing here when
we were doing our find_by_id for example or find_all, very similar.
The difference is just that we’re doing a count instead.
You could simply do a find_all and then count those. That is a different
technique, and either one will work. The difference is that one is going to
return a lot of data to you that you may not be going to use, and this is just
going to return a number, just a single simple number.
The way that we run our queries, if you will remember from find_by_sql is that
we do this result_set = database query. That’s what we ran on that. So we’ll do
that again here. But we’re not going use find_by_sql because we don’t want to
do any instantiation, which is what was happening there. So instead we’re just
going to run the database query and then out of that result_set, we’re going to
need to pull the value.
Now, let me show you the code for it first and then I’ll show you why.
We’re going to need to get the first row by doing fetch_array. We’re used to doing that,
and then we’re going to want to pull the first item out of that row,
array_shift, we’ll just get the first one, and that will return it to us.
Let me show you why. Let me open up Terminal and let me go into MySQL. So MySQL
user gallery, our password, and photo_ gallery. Now that we’re in there, let’s
try that method that we just did. So that’s SELECT COUNT FROM photographs. It
comes back and it says there are two.
Now, notice it returned it as a row, and this is the first item in the row. So
we’ll need to both fetch_array to get the row and then get that first field. So
it returns it as if it was a row in the database. Even though it’s just
returning a number, it doesn’t return a number, it returns a number inside a field,
inside a row, but that will then give us back the count that we’re looking for.
So because we have made this one of our common database methods, let’s go ahead
and add that to our other classes as well. Let’s just go into user, and right
below find_by_sql, let’s put in there as well. Let’s open up comment. There it is.
And I’ll jump down here, right below find_by_sql, we well add count_all.
Now they all have the ability to be counted in the same way. Again, eventually
those could be the kind of thing you could push up to database object.
So now that we have that method written, we’re able to get the total counts. So
we now have the three pieces that we need to do pagination. Now, we’re not
paginating yet. We have just done our research, because right now we’re still
finding all the photographs. What we want to do instead is just pull back a
subset of the photographs.
In the next movie we’ll create a pagination class that will make this task a lot easier.

In this movie we’ll see how we can write a pagination class that can help take
a lot of the grunt work out of doing pagination.
In the last movie we were able to get the current page, the records per page,
and the total record count, which are the three pieces we need to keep track of
in order to do pagination. But we’re still not paginating because right now
photograph is still doing find_all. What we really need is to do a find_by_sql
and use our new SQL statement that we saw before that uses Limit and Offset to
get just the subset of records that we want for the current page.
Now, that’s easy enough to do without doing it in an object oriented way.
We could simply do those calculations, compose some SQL, and then do our
find_by_sql statement. But the benefits of being object oriented really start
to pay off when we start wanting to have other elements on the page, like
showing information about the results. For example, results 1 through 10 out of
1,000. We would have to calculate over and over again a lot of information.
Then when we got to things like the page links, in order to figure out
whether there was a previous link or not, we would have to do a lot more
calculations and our code would start to get a little messy. Any time we have
that messy code it starts to be a case where we might think about putting
things into a class.
So we’re going to start out by doing this in an object oriented way and
creating a pagination class. So I’ll open up TextMate and start a new window.
Let’s go ahead and save this inside includes, and it’s going to be called
pagination.php. And we’ll just start our PHP tags.
Now, this is just simply going to be a class called pagination and that’s it.
It’s not going to inherit from anything. It’s not going to be using the
database. It’s just going to be a helper class that’s going to help make
pagination of our records a lot easier. One way that the pagination class is
going to help us is by keeping track of those three key variables for us:
current_page, per_page and total_count. In fact, since that’s going to be its
primary role, we’re going to go ahead and construct it using those.
We saw how to use construct earlier. We’re going to pass it in three arguments:
the page, per_page and total_count, and in each instance it’s just going to
make sure it’s an integer and assign it to that attribute. So now it has those stored.
So we can’t create a pagination object if we don’t have those
three pieces of information.
Now, we have given it some defaults: that the default is page 1, that it will
have 20 items per_page, you can make it 30 or whatever you prefer, and the
total_count, I went ahead and just gave it a default of zero.
So that you can quickly see how an object oriented approach like this pays off,
let’s do a calculation for how many total pages are in our results. We have the
total_count and we have the number per_ page, so we can easily figure out how
many pages there will be.
So we take total_count divided by per_ page, and we take the ceiling because
we want to always round up. We don’t want to round down because we’ll have some
leftover results. And that will tell us how many total pages there are.
Now we can simply ask our pagination, hey, tell me total_pages. We can also
tell it to give us the previous_page and the next_page. I have put in two more
methods here: previous_page, its current_ page – 1, next_page, current_page+1.
Now, you could write in some fancier checking for whether or not something has
a previous_page or has a next_page, so that we don’t accidentally try and go
too low or too high. I’ll leave that exercise to you. But I’ll add a couple
more methods that allow us to ask the pagination from the outside whether or
not it has a previous_page.
So these aren’t quite as error proof as they could be, but we do have a way
around it, which is to say, does this have a previous_page? And the answer to
that is, well, if you take that previous_page and it’s greater than one, then
yes, there is a previous_page greater than or equal to one. Return true,
otherwise false. There is not a previous_page. We’re at one already.
has_next_page does the same thing, but it uses total_pages that we just wrote
to say, well, is the next_page less than or equal to the total_pages?
Because if it’s more than the total_pages, then we don’t have a next_page. We’re at the end already.
So hopefully you can start to see why this is going to be very convenient for
us to be able to use our object to perform a lot of these calculations without
us having to stop and think about it each and every time. One area that’s
really going to help us is in calculating that offset. That’s a little bit
complicated. We want to make sure that we get it right. This object will always
get it right for us. We take the current_page minus one, times the items
per_page, and that’s the offset.
So now we can just ask our pagination object to give us the offset and
if we have provided the three parameters it knows the answers already.
Now, there is one last step that we want to do. We can save that and close it up.
We want to make sure that we go into initialize and just load that up.
So core objects, I’m going to put it right here below database object.
Make sure that you did load the other ones in here too: user, photograph, and
comment. Autoload may be picking those up for you. That’s maybe why you are not
getting an error. We have that autoload function. But we want to go ahead and
make sure that they get loaded in. Now that it’s done, we’re ready to paginate
and that’s what we’ll do in the next movie.

Now that we have written the pagination class that’s going to help us with our pagination,
we’re ready to actually paginate those photographs.
So here I’m in index.php. I’m going to start out by just commenting out this
previous find, use pagination instead. So we’ll leave it there,
but we’re actually not going to use it. Instead we’re going to now create a new
pagination object. We just created it, new Pagination. It’s going to want those
variables that we just set up above: page, per_page, and total_count.
So there we are. Now we have a new object created, and it has all the information that
we need about the pagination. We can just ask questions of it, essentially,
by calling its methods.
So then the only thing left to do is to find the records for this page. So
instead of finding all records, find just the records for this page. SELECT all
FROM photographs, make sure you have a space, LIMIT, and then we put in our
per_page value. That will be our limit. We talked about that before. Then
OFFSET. Instead of trying to calculate that offset, instead we’ll just ask the
pagination object, hey, use those parameters I gave you and tell me what the offset is.
Then from there it’s a simple matter of using the find_by_SQL statement that we
wrote earlier as a static call on photograph, using that SQL, and it will
return the photographs for that page.
Let’s try it. I’ll save it. Now I have got per_page = 3. I only have two
photographs in here now. Let’s start by adding more photographs. So we have got
two windows here, the first of which is in the Admin area, list_photos, Upload
a new photograph. We’ll browse for a new photograph. We have got flowers. Open,
flowers, Upload. Let’s add a new photograph, and this one is going to be roof.
Open. Roof. Oops, roof already exists.
What do I have? What am I missing? I have roof. I have bamboo.
Upload a new photograph. We’ll do the Buddhas. I’ll go ahead and put them all in there.
You can put other ones if you want. And Upload photos. I have got a wall and wood.
Take the last one. Upload a new photograph, Browse, wood. There we are.
So now I have got all of those photographs in there. If I go back to the Photo
Gallery, let’s go to page 1 first. See, I just see three of them and now
if at the end of it I put page = 2, I get the next three. I have six total,
so I’m seeing the first three and then I’m seeing the second three.
Typing in the links up here of course isn’t a great way to do it, instead what
we would really rather have are some pagination links that say next page,
etcetera, and that’s what we’ll look at creating in the next movie.

Now that we have our pagination working and we’re only seeing a subset of the
photos, what we need to create now are the navigation for our pages, so that
we can move forwards and backwards between the pages with the next link, previous link,
or links that let us jump to a certain desired page. I think as we do this,
you will really see where the pagination class is really going to pay dividends.
So here I’m in index.php and I have just added a little note here to remind us
that we need to page = and then whatever page we’re going to, to all links
where we want to maintain the current page.
So any page that needs to know what page to go back to, for example, we need to
pass that variable in and keep track of it. Or we need to store in the session
so that the page is in the session, the same we did message, for example.
And we can just pull it back out and know what page we should return to.
That becomes very important if we’re on the 10th page out of 20 pages and we
click on a link to go look at a photograph, we may want to keep track of the
fact that we were on page 10 so that we hit the back button to get back from
that photograph to the list again, we don’t go back to item number one.
So we’ll need to track that value. But that really applies mostly to when we
want to come back to this page. What we want to do is be able to move to a
different page and so we’re going to add some navigation links, we’re going to
do it right here below the photographs.
I am going to put in just a div for the pagination that’s going to clear both,
because we’re doing a float on these, right, float left. If you don’t know CSS
well that we need to do a clear both to make sure that the pagination drops
below all of those floated elements, so clear both we’ll do that for us.
Then we’re ready to start our PHP. I’ll come back here, PHP. So the first thing
is we don’t want to bother doing anything unless pagination is active. And the
way we can check that is if the total pages are greater than 1. So ask that
pagination object, do we have more than one page, we don’t need any next or
previous links at all if there is only one page. We can just skip this whole
thing. So that’s the first thing.
Now the second thing we want to add in is that next link, it will take us to
the next page. So I’m going to just skip a line here. So ask the pagination, do
you have a next page? So if it has next page, then index.php page = and then
whatever page we wanted to go to. And it will calculate that for us, it’s the
next page, we don’t have to stop and figure it out, its right there nice and
simple. And I went ahead and put a nice double arrow pointing in that
direction. That will take care of next.
Now once we go to the next page, of course we’ll want to be able to come back a page.
So we’ll need the same thing in reverse, which is the previous page. So
if it has a previous page or has next page, it will jump forwards and
backwards, to whatever the next page ought to be. Let’s try this out. We’ll go
back to Firefox. Here we are. I’m on page two. Let’s go back to page one for now.
And here we’re next, previous, next, previous. And you can watch the URL
up here to see where it’s pulling down that value from each page, okay.
Now it’s not much harder to iterate through the list of pages here, you can
just write a loop, I did it as a, for, loop. So I started with i = 1 and I said
from i <= total_pages incrementing i each time, go through and output
index.php. Now I have put a couple of spaces here in front of it, behind it
just to make sure that there is spaces between them. It’s up to you whether you
do that or whether you style them differently. But this will then take us to
page i whatever i is. So let’s just try and run that real quick. I’ll save it.
We’ll come back and now sure enough page 1, 2 and next. Page 1, page 2, page 1, page 2.
Now notice that it’s a link in both cases. What I really would like to do is
indicate what page I’m on now as well. We can do that. That’s not something
that’s that hard. We have done something similar before. It’s just an if-else
statement. And so I’m saying if i, the page that we’re going through as we
count up toward the total pages, if the page we’re looking at right now, they
are about to output is equal to page which is the current page then instead of
being a link just be span class selected around it.
So we’ll need to add some CSS for that but it will just be a number. Otherwise
make it a link. So I won’t be a link unless it’s a different page.
So let’s save that. Of course we’ll need to add that CSS as well. So let’s just
go back to our Finder and open up main. css and at the bottom here I’ll just put
in pagination .selected { font-weight: bold, and I gave it a color and let’s
see what that comes out as. That color is, from here up, it’s the burgundy
color. Let’s close that up, let’s go back to Firefox, and load it up.
Now we can see sure enough here is the page 2, page 1. It lets us know which
one it is. It’s not a link. It’s only a link if it’s a different page.
So, now we have full pagination, we’re finding the subset of results, we know
how many results there are total, and we can then generate links that will take
us to the page that we want. So as an exercise on your own, try and add the
same pagination to the staff area. We have a table that has a list of all the
photographs but what if that list got really long Let’s say we wanted to break
it at 5 or 10 to go to another page.
How would you do that? Try it on your own. It’s an exercise. I’m not going to
do it. It’s going to be included in your Exercise Files. But I think it will be
very useful for you to reinforce these concepts and make sure that you
understand what we’re doing with pagination.