Portfolio

Carl James Trelfa

PHP

PHP is very useful technology for creating dynamic web content.  Most of the PHP for this site is pretty straight forward - I did use a CMS system that I created way back in 2008 which makes building web sites really quick and easy. I did create a small api for the JavaScript Section, so take a look at that for a bit more PHP code.

The CMS code is fairly old and not coded in the style I tend to use today, it's not object oriented and uses some older php code that as of PHP 7 has been removed, so I won't be explaining the code for that.

The XAMPP installation I am using is set up for PHP 5.5 so the site probably isn't PHP 7 compatible, however, unlike the CMS system, it doesn't use any deprecated functions - for example, I'm using mysqli for database access, instead of the old mysql_connect method.

CMS System

I have four data sets (MySQL tables) set up in the CMS:

CMS Screen Shots

Main Navigation Site Content Sub Navigation

For the Main Navigation I can set the label to appear in the nav bar, the url associated with it and the order they appear.

For the Sub Navigation I can set the labels, order and url as well as select from a drop down which Main Navigation Section it belongs in.

For Content I can set the two Navigation sections it belongs in (with a special section for top-level pages, eg. techskills.html) and optionally use a Rich Text Editor to directly enter content in to the database or enter a filename that contains the content as a separate chunk of HTML/PHP. Most of the content uses the Rich Text Editor, but the JavaScript page uses a separate file. The final piece of the puzzle is the SEO stuff, Page Title, Keywords and Description.

Take a look at the JavaScript Section for information about PHP and database setup relating to that.

Database Access

The first thing we need to think about is our database.  I won't go in to the setup on PHPMyAdmin, I'll just cover accessing the data from PHP. My CMS actually handles adding new tables to the database, in order to set it up I simply import the SQL for a blank site and that's it.  I'm well versed in defining databases directly in MySQL and my CMS doesn't cover optimising your database with indexes - that is something that can only be done manually, it's pretty straight forward to test the efficiency of your MySQL queries so you can optimise in the right places.

I made a simple PHP class to handle database access - it's very simple and maybe even a bit unneccesary, however, it does serve as a good example of how to do OO PHP.

PHP MySQL Class

<?php
// @author Carl Trelfa
// MySQL access class
class MySQLAccess
{
    public $inited = false;
    private $dbConnection = null;
    
    // intialise a connection to our database
    public function init($hostname, $username, $password, $dbname) {
        $this->inited = false;
        $this->dbConnection = new mysqli($hostname, $username, $password, $dbname);
        if ($this->dbConnection->connect_error) {
            die("Unable to connect to MySQL");
        } else {
            $this->inited = true;
        }
    }
    
    public function closeConnection() {
        $this->inited = false;
        $this->dbConnection->close();
    }
    
    // seems a bit extraneous, but you never know we might need to add to it
    public function freeResult($mysqlResultSet) {
        $mysqlResultSet->free();
    }
    
    public function executeQuery($mysqlQuery) {
        if ($this->inited) {
            return $this->dbConnection->query($mysqlQuery);
        } else {
            return null;
        }
    }
    
    public function fetchNextRow($mysqlResultSet) {
        if ($this->inited) {
            return $mysqlResultSet->fetch_assoc();
        } else {
            return null;
        }
    }
}
?>

Now I can access the database with just a handful of lines of code.  I use this to pull all the data from the Navigation tables and pull the content data we need to display from the Content table.

Here's how I pull the Main Navigation from the Database and create a PHP Array containing all the Navigation data:

Fetch Main Navigation

    // Instantiate and init our MySQLAccess class
    require 'libs/MySQLAccess.php';
    $ourDB = new MySQLAccess();
    $ourDB->init($hostname, $username, $password, $dbname);
   
    // ... there is more code here
   
    $mainNavData = [];
    $mysqlQuery = "SELECT `id`, `label`, `seourl` FROM `mainnav` ORDER BY `order`";
    $result = $ourDB->executeQuery($mysqlQuery);
    if ($result) {
        while ($row = $ourDB->fetchNextRow($result)) {
            array_push($mainNavData, $row);
            // ... it does a couple more things here
        }
        $ourDB->freeResult($result);
    }

I actually pull the content from the database first - it's tagged with the relevant sections so I can figure out from that which section of the site to highlight on the navigation. The query string that is passed in to the main index.php file helps me to find the correct content by including a WHERE clause in the MySQL query string (see the SEO Section for information on how the site goes from php.html to index.php and a query string).  If there's no matching content, I just revert to the Home Page content, although you could display a fancy 404 page with maybe a site search or recommended articles instead.

So now from the Content I can tell which Main Navigation and Sub Navigation section this page belongs in.  A few lines of PHP code later and I can use this data to dynamically output the Navigation bars to represent the section of the site you are viewing.

Logic Flow

Ok the entire site has a single entry point at index.php.  That file looks something like this:

index.php

<?php
    include 'views/htmlchunks/pre-header.php';
?>

<!DOCTYPE html>
<html lang="en">
<?php
    include 'views/htmlchunks/html-header.php';
?>

    <body>
        <div class="mainPageHolder">
            
<?php
    include 'views/htmlchunks/page-header.php';
    include 'views/htmlchunks/main-nav.php';
    include 'views/htmlchunks/sub-nav.php';
    ?>
    <!-- START OF MAIN CONTENT -->
    <?php
    if (!empty($mainAltContent)) {
        ?>
        
        <div class="mainContentHolder">
            
            <?php
                echo $mainAltContent."/n";
            ?>
            
        </div>
        
        <?php
    }
    if (!empty($mainContentViewChunk)) {
        $contentInc = "views/htmlchunks/".$mainContentViewChunk."-content.php";
        include $contentInc;
    }
    ?>
    <!-- END OF MAIN CONTENT -->
    <?php
    if ($showCrumbs) {
        include 'views/htmlchunks/crumbtrail.php';
    }
    include 'views/htmlchunks/footer.php';
?>

        </div>
    </body>
</html>

As you can see, the site is split up in to managable chunks which are included in to the final output.  If we want to change the site header, we just edit the page-header.php file. 

Some PHP code needs to happen before we output anything to the browser, such as cookies - this is where pre-header.php comes in.  This file also handles pulling everything out of the database and figuring out which Navigation Sections we are looking at and puts the content data in to two variables (one for the Rich Text Editor content and one for content in seperate files).

Some files (eg. the Main and Sub Navigation bars) have a small amount of PHP code to dynamically highlight the correct sections.

Simple!

It would be fairly easy to use more OOP code on the site, but for such a small site it seems unecessary. If I had plans to significantly expand the site it would be pretty trivial to refactor what I have here. Prizechinko is a good example of a much larger, all OOP PHP project that I worked on.

Home > Technical Skills > PHP