Build an eCommerce Website with PHP – Part 2 – PHP & JS

The DOM as it’s represented in the browser

PHP Basic Introduction

PHP also known as Hypertext Preprocessor was initially developed as a simple CGI application for interpreting form defined in HTML and processing them on the server side.

PHP (PHP current version 5.3) is a powerful package that provides an easy to learn programming language for generating HTML files.  It’s familiar, C-based syntax and the fact that’s it’s free to use make it a very attractive alternative to other server side languages like ASP.NET or Ruby.

I’ve decided to use PHP for this application because of the low web hosting prices for PHP websites and its ease of use and general reliability.

Another great feature of PHP is its vast support for numerous database systems. The following database systems are supported by PHP:

Adabas D InterBase PostgreSQL
dBase FrontBase Sesam
Empress mSQL Solid
FilePro Direct MS-SQL Sybase
Hyperwave MySQL Velocis
IBM DB2 ODBC Unix dbm
Informix Oracle
Ingres Ovrimos

PHP offers support for multiple mail services and protocols including IMAP, SNMP, NNTP, POP3 and HTTP. This makes sending emails directly from the server side a very easy and straightforward task.

PHP instructions can be interwoven with HTML code. The only requirement is that PHP instructions need to be placed between two special delimiters:

    ...some code...

Any instructions between these two delimiters will be interpreted on the server side. After PHP code is executed, the server will serve the generated HTML code to the client.

Let’s take for example the following document:

<!doctype html>
	<title><?php echo 'Hello World!'?></title>
	<?php echo '<h1>Hello world</h1>'?>

This will be processed by the server and then served to the client in the following form:

<!doctype html>
	</title>Hello World!</title>
	<h1>Hello world</h1>

As you can see, all of the PHP code is removed by the server once it’s been executed. The client will never be able to see the source code that has generated the page. The two echo functions that are used will output two strings to the HTML document. The first is the site title and the second is a <h1> tag.

As you can see there are really no limits to what can be done with PHP and that’s why it’s become the standard for server side programming.

JavaScript Basic Introduction

JavaScript or JS is a widely used scripting language that’s mostly used in combination with HTML. It uses a simple, easy to learn C-style syntax but unlike PHP doesn’t provide support for traditional Object Oriented Programming concepts. This can be a challenge for developers who’ve worked only with classic OOP languages like C.

JavaScript has been in use since the early 90’s but only recently has it become a truly popular programming language with the rise of technologies such as AJAX and HTML5.

JavaScript code can be placed in external .js files or in the HTML document within the <head> or <body> tags.

An important thing to note about JavaScript is that it can only access HTML elements that exist in the DOM. The DOM or Document Object Model is the way that an HTML document is represented inside the browser. When an internet browser opens a HTML document it will generate a DOM for it. It will then traverse this DOM and render the web page to the screen.  If JavaScript code is set to run before the DOM is generated by the browser then this code can access only HTML elements that are present in the DOM.

Basically what this means is that JavaScript code can only access HTML elements that are declared before it. This is the reason that some developers place their code at the end of the document so that it can access all of the elements on the page.

The DOM as it’s represented in the browser

Declaring variables in JavaScript is done by using the following syntax:

var foo = “Hello world!”;

JavaScript is a loosely typed language, meaning that there’s no need to declare variable types, the language does this automatically based on the value you assign to a variable. In the example above, the variable foo will be of type String and it will contain the following string “Hello world!”.


A function is a block of code that executes only when you tell it to execute. It can be when an event occurs, like when a user clicks a button, or from a call within your script, or from a call within another function.
Functions can be placed both in the <head> and in the <body> section of a document.

function functionname()
    ...some code...


jQuery is a JavaScript library designed to simplify the client-side scripting of HTML. It’s free to use, open source and has seen a huge increase in popularity over the years. The reason why it has become so popular is that it allows programmers to create complex animations and effects with relative ease and without requiring vast knowledge in programming or JavaScript.

The heart of jQuery is its powerful selector engine. This allows us to easily access and modify any HTML tag on the page. For example the following instruction will target every <div> on the page that has a class of .red


We can then modify these elements; the following code will change the background color of these elements to green:


Creating configuration files and rendering the main page

Before I could get started on coding the main store pages in PHP, I needed to set some configuration variables so that I could later access them from any page on the site. I also needed to create a couple of function for displaying the page head (this is common for all the pages of the site) and checking if the current user is logged in.

All of these things are located in the functions.php file.  The first lines of this file contain general configuration settings such as the site title and database login details.

//================== Global Variables====================

$site_title = 'Magazin Online';
$site_url = 'http://localhost/alarmebuzau/';
$document_path = $site_url;

//================== Database Connection====================

$dbUser = "AA";
$dbPass = "aa";
$dbServer = "localhost";

Following these is the function that renders the document head for a page. Some key elements to note are the inclusion of jQuery library <script type="text/javascript" language="javascript" src="jquery.js"></script> and the site title <title>Alarme Buzau</title>. Both of these are generated with PHP based on the configuration variables described above. The PHP code that renders the head is as follows:

function display_head(){
	global $site_title, $site_url, $document_path;
	echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">' . "\n"
	.'<html xmlns="" lang="ro">'. "\n"
	.'<head>'. "\n"
	.'<title>'.$site_title.'</title>'. "\n"
	.'<link href="'.$document_path .'css/style.css" media="screen" rel="stylesheet" type="text/css" />'. "\n"
	.'<link rel="shortcut icon" href="'.$document_path .'images/favicon.ico"/>'. "\n"
	.'<script type="text/javascript" language="javascript" src="'.$document_path .'script/js/jquery-1.7.2.min.js"></script>'. "\n"
	.'<script type="text/javascript" language="javascript" src="'.$document_path .'script/js/jquery.roundabout.min.js"></script>'. "\n"
	.'<script type="text/javascript" src="'.$document_path.'script/jwplayer/jwplayer.js"></script>'."\n"
	.'</head>' . "\n";

The next and final function in functions.php is used to check if the user is logged in. Every time a customer logs in, PHP will set a value for the following variable $_SESSION['user_email']. This variable is stored in PHP’s session which means it will be only available for the current customer. Each customer has his own session.

The function checks if the above mentioned variable has been set and if so it will return true; otherwise it will return false indicating that the customer is not logged in.

function isLoggedIn(){
    if(isset($_SESSION['user_email']) && $_SESSION['user_email'] != ""){
        return true;
        return false;

Having taken care of the configuration details, the next thing I coded was the landing page.

The landing page or home page is the first page that a customer sees when he enters the site’s address in a browser.  The general layout used on this page can be seen in all other pages of the site, thus maintaining a consistent theme.  The only difference between two pages will be the content area. The basic template for these pages is presented below.

	include 'script/functions.php';
<?php include 'header.php'; ?>

<div id="carousel-container">
	<!--carousel goes here-->

<div class="wrapper">
	<!--content goes here-->
<?php include 'footer.php'; ?>

<script type="text/javascript">
 	<!--javascript goes here-->

The first two lines are written in PHP. They’re responsible for accessing functions.php so that the variables and functions declared there are available in the current page. Then the display_head() function is called that will display the page head.

The next part is responsible for including the page header include 'header.php'. This header is the top menu that appears on all pages. The file that’s included contains both HTML and PHP code that is directly inserted in the current page.
The last important part to note here is the inclusion of the footer which is done in similar way as the header.

The carousel is created using the Roundabout JavaScript library. In order to make it run two things are required: HTML markup and JavaScript code.
For the former all that was needed was a simple unordered list <ul> in which each list item is an image.

<div id="carousel-container">
	<ul id="carousel">
		<li><img src="<?php echo $document_path ?>images/sigla.gif" alt=""/></li>

And on the JavaScript side, we include the library in the document head and write the necessary code so that it’s properly initialized.

<script type="text/javascript" language="javascript" 
src="'.$document_path .'script/js/jquery.roundabout.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
	var carousel = $('#carousel').hide();	
		//initialize the carousel
		carousel.roundabout({autoplay:true, autoplayDuration:6000});	
		//display the carousel;

Using jQuery like this $(document).ready allows us to run the code after the page has finished loading. This way I was able to avoid problems with the DOM that can arise when you run JavaScript code before the DOM is completely loaded.

To display the products on the main page I wrote PHP code that goes through the categories and products tables. The steps needed to do this are as follows:

  1. Connect to the database
    $conn = oci_connect($dbUser, $dbPass, $dbServer);
  2. Select from the database only the parent categories
    $sql  = oci_parse($conn, 'select * from categories where parent is null');
  3. Each of these parent categories corresponds to one of the four columns on the page so the code will render a column for each row that’s returned by the database query.
    for($i=0; $i<4; $i++){ 
        $row = oci_fetch_assoc($sql);
    <li>For each of the main categories go throught the database and search for subcategories.
    $sql2 = oci_parse($conn, "select * from categories where parent = '" . $row["NAME"] . "'");
  4. Render the subcategory and search for subcategories for it.
    $sql3 = oci_parse($conn, "select * from categories where parent = '" . $row2["NAME"] . "'");
  5. The menu is now rendered. When a user hovers the mouse over one of the 4 main column titles he will be shown a menu with subcategories. To enable this functionality, I used JavaScript.
    $(".menu li").hover(function(){
    $('ul:first',this).css('visibility', 'visible');
    }, function(){
    $('ul:first',this).css('visibility', 'hidden');
  6. Finally, the code will display the products in each category.
    $sql4 = oci_parse($conn, "select * from products where category_pk = '" . $cat . "'");
    <div class="prodDescription" style="margin:15px 0 0 0;">
    <a href="<?php echo $document_path ?>product.php?prod_id=<?php echo $row4["ID"] ?>"><?php echo $row4["TITLE"]; ?></a>
    <a href="<?php echo $document_path ?>product.php?prod_id=<?php echo $row4["ID"] ?>">
        <img class="thumb" src="img/<?php echo $row4["PHOTO"]; ?>" width="170" height="170" alt="<?php echo $row4["TITLE"]; ?>" />
    <span class="details">
        <?php echo $row4["DESC1"]; ?><br/>
        <?php echo $row4["DESC2"]; ?><br/>
        <?php echo $row4["DESC3"]; ?><br/>
        <?php echo $row4["DESC4"]; ?><br/>
        <?php echo $row4["DESC5"]; ?><br/>
        <?php echo $row4["DESC6"]; ?><br/>
    <?php if(isset($row4["SALE"])){?>
    <span>Pret: <?php echo $row4["PRICE"]; ?>&nbsp;Lei (cu TVA)</span>
    <span>Reducere: <?php echo $row4["SALE"]; ?> <br/></span>
    <span>Pret: <?php echo $row4["PRICESALE"]; ?>(cu TVA)<br/></span>
        } else{
    <span>Pret: <?php echo $row4["PRICE"]; ?>(cu TVA)<br/></span>
    <?php } ?>
Series Navigation