Building a Website with PHP, MySQL and jQuery Mobile, Part 2

This is the second part of a two-part tutorial, in which we use PHP, MySQL and jQuery mobile to build a simple computer web store. In the previous part we created the models and the controllers, and this time we will be writing our views.

jQuery mobile

First, lets say a few words about the library we will be using. jQuery mobile is a user interface library that sits on top of jQuery and provides support for a wide array of devices in the form of ready to use widgets and a touch-friendly development environment. It is still in beta, but upgrading to the official 1.0 release will be as simple as swapping a CDN URL.

The library is built around progressive enhancement. You, as the developer, only need to concern yourself with outputting the correct HTML, and the library will take care of the rest. jQuery mobile makes use of the HTML5 data- attributes and by adding them, you instruct the library how it should render your markup.

In this tutorial we will be using some of the interface components that this library gives us – listsheaderand footer bars and buttons, all of which are defined using the data-role attributes, which you will see in use in the next section.

Rendering Views

The views are PHP files, or templates, that generate HTML code. They are printed by the controllers using the render() helper function. We have 7 views in use for this website – _category.php_product.php,_header.php_footer.phpcategory.phphome.php and error.php, which are discussed later on. First, here is render() function:


01 /* These are helper functions */
03 function render($template,$vars array()){
05     // This function takes the name of a template and
06     // a list of variables, and renders it.
08     // This will create variables from the array:
09     extract($vars);
11     // It can also take an array of objects
12     // instead of a template name.
13     if(is_array($template)){
15         // If an array was passed, it will loop
16         // through it, and include a partial view
17         foreach($template as $k){
19             // This will create a local variable
20             // with the name of the object's class
22             $cl strtolower(get_class($k));
23             $$cl $k;
25             include "views/_$cl.php";
26         }
28     }
29     else {
30         include "views/$template.php";
31     }
32 }

The first argument of this function is the name of the template file in the views/ folder (without the .phpextension). The next is an array with arguments. These are extracted and form real variables which you can use in your template.

There is one more way this function can be called – instead of a template name, you can pass an array with objects. If you recall from last time, this is what is returned by using the find() method. So basically if you pass the result of Category::find() to render, the function will loop through the array, get the class names of the objects inside it, and automatically include the _category.php template for each one. Some frameworks (Rails for example) call these partials.

Computer Store with PHP, MySQL and jQuery Mobile

Computer Store with PHP, MySQL and jQuery Mobile

The Views

Lets start off with the first view – the header. You can see that this template is simply the top part of a regular HTML5 page with interleaved PHP code. This view is used in home.php and category.php to promote code reuse.


01 <!DOCTYPE html>
02 <html>
03     <head>
04     <title><?php echo formatTitle($title)?></title>
06     <meta name="viewport" content="width=device-width, initial-scale=1" />
08     <link rel="stylesheet" href="" />
09     <link rel="stylesheet" href="assets/css/styles.css" />
10     <script type="text/javascript" src=""></script>
11     <script type="text/javascript" src=""></script>
12 </head>
13 <body>
15 <div data-role="page">
17     <div data-role="header" data-theme="b">
18         <a href="./" data-icon="home" data-iconpos="notext" data-transition="fade">Home</a>
19         <h1><?php echo $title?></h1>
20     </div>
22     <div data-role="content">

In the head section we include jQuery and jQuery mobile from jQuery’s CDN, and two stylesheets. The body section is where it gets interesting. We define a div with the data-role=”page” attribute. This, along with the data-role=”content” div, are the two elements required by the library to be present on every page.

The data-role=”header” div is transformed into a header bar. The data-theme attribute chooses one of the 5 standard themes. Inside it, we have a link that is assigned a home icon, and has its text hidden. jQuery Mobile comes with a set of icons you can choose from.

The closing tags (and the footer bar) reside in the _footer.php view:


1     </div>
3     <div data-role="footer" id="pageFooter">
4         <h4><?php echo $GLOBALS['defaultFooter']?></h4>
5     </div>
6 </div>
8 </body>
9 </html>

Nothing too fancy here. We only have a div with the data-role=”footer” attribute, and inside it we print the globally accessible $defaultFooter variable, defined in includes/config.php.

Neither of the above views are printed directly by our controllers. They are instead used bycategory.php and home.php:


01 <?php render('_header',array('title'=>$title))?>
03 <p>Welcome! This is a demo for a ...</p>
04 <p>Remember to try browsing this ...</p>
06 <ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="b">
07     <li data-role="list-divider">Choose a product category</li>
08     <?php render($content) ?>
09 </ul>
11 <?php render('_footer')?>

If you may recall, the home view was rendered in the home controller. There we passed an array with all the categories, which is available here as $content. So what this view does, is to print the header, and footer, define a jQuery mobile listview (using the data-role attribute), and generate the markup of the categories passed by the controller, using this template (used implicitly by render()):


1 <li <?php echo ($active == $category->id ? 'data-theme="a"' '') ?>>
2 <a href="?category=<?php echo $category->id?>" data-transition="fade">
3     <?php echo $category->name ?>
4     <span class="ui-li-count"><?php echo $category->contains?></span></a>
5 </li>

Notice that we have a $category PHP variable that points to the actual object this view is being generated for. This is done in lines 24/25 of the render function. When the user clicks one of the links generated by the above fragment, he will be taken to the /?category=someid url, which will show thecategory.php view, given below.

01 <?php render('_header',array('title'=>$title))?>
03 <div class="rightColumn">
04     <ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="c">
05         <?php render($products) ?>
06     </ul>
07 </div>
09 <div class="leftColumn">
10     <ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="b">
11         <li data-role="list-divider">Categories</li>
12         <?php render($categories,array('active'=>$_GET['category'])) ?>
13     </ul>
14 </div>
16 <?php render('_footer')?>

This file also uses the header, footer and _category views, but it also presents a column with products (passed by the category controller). The products are rendered using the _product.php partial:

1 <li class="product">
2     <img src="assets/img/<?php echo $product->id ?>.jpg" alt="<?php echo $product->name ?>" />
3     <?php echo $product->name ?> <i><?php echo $product->manufacturer?></i>
4     <b>$<?php echo $product->price?></b>
5 </li>

As we have an image as the first child of the li elements, it is automatically displayed as an 80px thumbnail by jQuery mobile.

One of the advantages to using the interface components defined in the library is that they are automatically scaled to the width of the device. But what about the columns we defined above? We will need to style them ourselves with some CSS3 magic:


01 media all and (min-width650px){
03     .rightColumn{
04         width:56%;
05         float:right;
06         margin-left:4%;
07     }
09     .leftColumn{
10         width:40%;
11         float:left;
12     }
14 }
16 .product i{
17     display:block;
18     font-size:0.8em;
19     font-weight:normal;
20     font-style:normal;
21 }
23 .product img{
24     margin:10px;
25 }
27 .product b{
28     positionabsolute;
29     right15px;
30     top15px;
31     font-size0.9em;
32 }
34 .product{
35     height80px;
36 }

Using a media query, we tell the browser that if the view area is wider than 650px, it should display the columns side by side. If it is not (or if the browser does not support media queries) they will be displayed one on top of the other, the regular “block” behavior.

Reference :

Building a Website with PHP, MySQL and jQuery Mobile, Part 1

In this two-part tutorial, we will be building a simple website with PHP and MySQL, using the Model-View-Controller (MVC) pattern. Finally, with the help of the jQuery Mobile framework, we will turn it into a touch-friendly mobile website, that works on any device and screen size.

In this first part, we concentrate on the backend, discussing the database and MVC organization. In part two, we are writing the views and integrating jQuery Mobile.

The File Structure

As we will be implementing the MVC pattern (in effect writing a simple micro-framework), it is natural to split our site structure into different folders for the models, views and controllers. Don’t let the number of files scare you – although we are using a lot of files, the code is concise and easy to follow.

The Directory Structure

The Directory Structure

The Database Schema

Our simple application operates with two types of resources – categories and products. These are given their own tables – jqm_categories, and jqm_products. Each product has a category field, which assigns it to a category.

jqm_categories Table Structure

jqm_categories Table Structure

The categories table has an ID field, a name and a contains column, which shows how many products there are in each category.

jqm_products Table Structure

jqm_products Table Structure

The product table has a namemanufacturerprice and a category field. The latter holds the ID of the category the product is added to.

You can find the SQL code to create these tables in tables.sql in the download archive. Execute it in the SQL tab of phpMyAdmin to have a working copy of this database. Remember to also fill in your MySQL login details in config.php.

The Models

The models in our application will handle the communication with the database. We have two types of resources in our application – products and categories. The models will expose an easy to use method – find() which will query the database behind the scenes and return an array with objects.

Before starting work on the models, we will need to establish a database connection. I am using the PHP PDO class, which means that it would be easy to use a different database than MySQL, if you need to.


02     This file creates a new MySQL connection using the PDO class.
03     The login details are taken from includes/config.php.
04 */
06 try {
07     $db new PDO(
08         "mysql:host=$db_host;dbname=$db_name;charset=UTF-8",
09         $db_user,
10         $db_pass
11     );
13     $db->query("SET NAMES 'utf8'");
14     $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
15 }
16 catch(PDOException $e) {
17     error_log($e->getMessage());
18     die("A database error was encountered");
19 }

This will put the $db connection object in the global scope, which we will use in our models. You can see them below.


01 class Category{
03     /*
04         The find static method selects categories
05         from the database and returns them as
06         an array of Category objects.
07     */
09     public static function find($arr array()){
10         global $db;
12         if(empty($arr)){
13             $st $db->prepare("SELECT * FROM jqm_categories");
14         }
15         else if($arr['id']){
16             $st $db->prepare("SELECT * FROM jqm_categories WHERE id=:id");
17         }
18         else{
19             throw new Exception("Unsupported property!");
20         }
22                 // This will execute the query, binding the $arr values as query parameters
23         $st->execute($arr);
25         // Returns an array of Category objects:
26         return $st->fetchAll(PDO::FETCH_CLASS, "Category");
27     }
28 }

Both models are simple class definitions with a single static method – find(). In the fragment above, this method takes an optional array as a parameter and executes different queries as prepared statements.

In the return declaration, we are using the fetchAll method passing it the PDO::FETCH_CLASS constant. What this does, is to loop though all the result rows, and create a new object of the Category class. The columns of each row will be added as public properties to the object.

This is also the case with the Product model:


01 class Product{
03     // The find static method returns an array
04     // with Product objects from the database.
06     public static function find($arr){
07         global $db;
09         if($arr['id']){
10             $st $db->prepare("SELECT * FROM jqm_products WHERE id=:id");
11         }
12         else if($arr['category']){
13             $st $db->prepare("SELECT * FROM jqm_products WHERE category = :category");
14         }
15         else{
16             throw new Exception("Unsupported property!");
17         }
19         $st->execute($arr);
21         return $st->fetchAll(PDO::FETCH_CLASS, "Product");
22     }
23 }

The return values of both find methods are arrays with instances of the class. We could possibly return an array of generic objects (or an array of arrays) in the find method, but creating specific instances will allow us to automatically style each object using the appropriate template in the views folder (the ones that start with an underscore). We will talk again about this in the next part of the tutorial.

There, now that we have our two models, lets move on with the controllers.

Computer Store with PHP, MySQL and jQuery Mobile

Computer Store with PHP, MySQL and jQuery Mobile

The controllers

The controllers use the find() methods of the models to fetch data, and render the appropriate views. We have two controllers in our application – one for the home page, and another one for the category pages.


01 /* This controller renders the home page */
03 class HomeController{
04     public function handleRequest(){
06         // Select all the categories:
07         $content = Category::find();
09         render('home',array(
10             'title'     => 'Welcome to our computer store',
11             'content'   => $content
12         ));
13     }
14 }

Each controller defines a handleRequest() method. This method is called when a specific URL is visited. We will return to this in a second, when we discuss index.php.

In the case with the HomeControllerhandleRequest() just selects all the categories using the model’s find() method, and renders the home view (includes/views/home.php) using our render helper function (includes/helpers.php), passing a title and the selected categories. Things are a bit more complex inCategoryController:


01 /* This controller renders the category pages */
03 class CategoryController{
04     public function handleRequest(){
05         $cat = Category::find(array('id'=>$_GET['category']));
07         if(empty($cat)){
08             throw new Exception("There is no such category!");
09         }
11         // Fetch all the categories:
12         $categories = Category::find();
14         // Fetch all the products in this category:
15         $products = Product::find(array('category'=>$_GET['category']));
17         // $categories and $products are both arrays with objects
19         render('category',array(
20             'title'         => 'Browsing '.$cat[0]->name,
21             'categories'    => $categories,
22             'products'      => $products
23         ));
24     }
25 }

The first thing this controller does, is to select the category by id (it is passed as part of the URL). If everything goes to plan, it fetches a list of categories, and a list of products associated with the current one. Finally, the category view is rendered.

Now lets see how all of these work together, by inspecting index.php:


01 /*
02     This is the index file of our simple website.
03     It routes requests to the appropriate controllers
04 */
06 require_once "includes/main.php";
08 try {
10     if($_GET['category']){
11         $c new CategoryController();
12     }
13     else if(empty($_GET)){
14         $c new HomeController();
15     }
16     else throw new Exception('Wrong page!');
18     $c->handleRequest();
19 }
20 catch(Exception $e) {
21     // Display the error page using the "render()" helper function:
22     render('error',array('message'=>$e->getMessage()));
23 }

This is the first file that is called on a new request. Depending on the $_GET parameters, it creates a new controller object and executes its handleRequest() method. If something goes wrong anywhere in the application, an exception will be generated which will find its way to the catch clause, and then in the error template.

One more thing that is worth noting, is the very first line of this file, where we require main.php. You can see it below:


01 /*
02     This is the main include file.
03     It is only used in index.php and keeps it much cleaner.
04 */
06 require_once "includes/config.php";
07 require_once "includes/connect.php";
08 require_once "includes/helpers.php";
09 require_once "includes/models/product.model.php";
10 require_once "includes/models/category.model.php";
11 require_once "includes/controllers/home.controller.php";
12 require_once "includes/controllers/category.controller.php";
14 // This will allow the browser to cache the pages of the store.
16 header('Cache-Control: max-age=3600, public');
17 header('Pragma: cache');
18 header("Last-Modified: ".gmdate("D, d M Y H:i:s",time())." GMT");
19 header("Expires: ".gmdate("D, d M Y H:i:s",time()+3600)." GMT");

This file holds the require_once declarations for all the models, controllers and helper files. It also defines a few headers to enable caching in the browser (PHP disables caching by default), which speeds up the performance of the jQuery mobile framework.

Continue to Part 2

With this the first part of the tutorial is complete! Continue to part 2, where we will be writing the views and incorporate jQuery Mobile. Feel free to share your thoughts and suggestions in the comment section below.

Reference :