« Back to Index

The last time I wrote any real PHP (of any production worth) was back in 2006 (it’s now December 2012). I thought I would share some potentially terrible PHP code I wrote today whilst trying to refresh my memory. Definitely feel free to have a good laugh, but what would be even better would be some constructive criticism. This isn’t supposed to be anything remotely near finished code. The purpose was to get me back into the feel for writing PHP. If there are suggestions about what I’ve written (things I should avoid for example) then I’d love to hear them. Thanks!

View original Gist on GitHub

1. Database.php

<?php
    class Database {
        private $_dbconnection;

        /*
            @description 
            Constructor that creates a new instance of a PDO connection.
            
            @param username     {String} username access
            @param password     {String} password access
            @param host         {String} host information (either localhost or ip address, defaults to localhost)
            @param dbname       {String} database name to access (defaults to stormtest)
            @param errortype    {Object} sets the error mode (defaults to ERRMODE_SILENT)
            @return             {Object} new class instance object is returned
         */
        public function __construct ($username, $password, $host = 'localhost', $dbname = 'mydemodb', $errortype = PDO::ERRMODE_SILENT) {
            try {
                $this->_dbconnection = new PDO('mysql:host=' . $host . ';dbname=' . $dbname, $username, $password);
                $this->_dbconnection->setAttribute(PDO::ATTR_ERRMODE, $errortype);

                /*
                    // Different error settings that can be used...

                    $_dbconnection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );    // Standard
                    $_dbconnection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );   // Useful for debuggin
                    $_dbconnection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); // Shows an exception and hides all other important data
                 */
            } catch (PDOException $error) {
                die($error->getMessage()); // Ideally we'd do something better here than just die!
            }
        }

        /*
            @description 
            Fetch data from table using specified SQL command and returns data as either an Array or an Object (depending on what the user specifies).
            
            @param sql              {String}        The SQL command to execute
            @param response_type    {Object}        Optional response type (defaults to Array)
            @return results         {Object|Array}  Returns either an Array or an Object (depending on what the user specified)
         */
        public function fetch ($sql, $response_type = PDO::FETCH_ASSOC) {
            $query = $this->_dbconnection->query($sql);
            $query->setFetchMode($response_type);
            $results = $query->fetchAll(); // was originally using `fetch` but realised that only returns first result
            return $results;
        }

        // Close the database connection
        public function close () {
            $this->_dbconnection = null;
        }
    }
?>

2. Basic Demo.php

<?php

// CONFIGURE ERROR MESSAGES
    ini_set('display_errors',1);
    error_reporting(E_ALL);

// PULL IN OUR DATABASE CLASS
    require 'Database.php';

// GENERIC CONNECTION (REUSED A FEW TIMES BELOW)
    $db_connection = new Database('root', 'mydemopass');
    
// EXAMPLE OF BASIC QUERY
    $results_array = $db_connection->fetch('SELECT * FROM testing');
    $results_object = $db_connection->fetch('SELECT * FROM testing', PDO::FETCH_OBJ);

    print_r($results_array);
        echo '<br><hr>';
    print_r($results_object);
        echo '<br><hr>';

// EXAMPLE OF JOINING DATA VIA FOREIGN KEY
    $sql = 'SELECT * FROM testing INNER JOIN roles ON testing.user_role = roles.role_id'; // In MySQL we set-up `user_role` to be an index/foreign key which points to the `roles` table
    $results_full_object = $db_connection->fetch($sql, PDO::FETCH_OBJ);

    print_r($results_full_object);
        echo '<hr>';

    /*
        An Array wraps multiple Objects in the results.
        So we have to loop through the Array first before we can access the Objects within.
     */
    foreach ($results_full_object as $index) {
        
        foreach ($index as $key => $value) {
            echo $key . ': ' . $value . '<br>';

            /*
                // This loop will display something like this...

                user_id: 1
                user_name: Joe
                user_surname: Bloggs
                user_age: 30
                user_role: 1
                role_id: 1
                role_name: Manager
                user_id: 1
                user_name: Bob
                user_surname: Smith
                user_age: 99
                user_role: 2
                role_id: 2
                role_name: Developer
             */
        }
    }

// WE'RE DONE, LETS GO!
    $db_connection->close();

?>