Build Internet has a brand new theme, and that's only the beginning. Read the full story or hide this bar

Creating Your First PHP Application: Part 1

Creating Your First PHP Application: Part 1

Editor’s Note: This is a guest post from Brian Muse, our lead developer on You Rather. He’ll be guiding you through a three part journey of PHP applications over the next few days.

This tutorial is intended for readers who know the very basics of PHP and Object Oriented Programming (OOP) and would like to create a basic web application.

To make this a little bit clearer, I’ve split this tutorial up into three separate posts. Each post will cover a major step in setting up a basic PHP web application.

Series Overview

We’ve got a lot of ground to cover. Here’s a general outline about what to expect from each post in this series:

Part 1 – Setting up the project and creating your first class

  • Creating an outline of the project
  • Setting up your files and folders
  • Creating a class to handle database operations: DB.class.php

Part 2 – Building the rest of the backend

  • Creating a User class
  • Creating a UserTools class
  • Registration / Logging in / Logging out

Part 3 – Building the front end

  • Forms
  • Form Handling
  • Displaying session data

Setting up the Project

Creating a Road Map

It’s always a good idea to know where you’re going. Before you start creating and coding files it’s best to set your goals, map out the project and make decisions about your folder structure and what files you’ll need to make to accomplish your goal. The goal for this project is fairly simple: Create a basic PHP web application with user registration, the ability to log in and out and a way for users to update their settings.

Files and Folder Structure

An OOP PHP project utilizes classes and objects to perform many of the operations that the application requires. When planning, you should think about what classes you will need. For this project we’ll be making three classes. The first is the User class, which will hold information about a particular user and a basic save() function. Another class, UserTools will contain functions that have to do with users, such as login(), logout(), etc. The final class is the first class we’ll be coding: the database class. This class will handle connecting to the database, updating, inserting new rows, retrieving rows, and more.

Aside from classes, we’ll utilize a file called global.inc.php. This file will be called on every page and will perform general operations that we commonly require. For example, it is this file that will handle connecting to the database on each page.

The rest of the files are the pages the user will navigate around. These include index.php, register.php, login.php, logout.php, settings.php and welcome.php.

The final directory structure should look like the image below:

Creating your database and users table

You must have MySQL installed on your server to continue. You’ll first have to create a new database for your application. Within that database to create the users table we’ll be using for this tutorial, use the following SQL:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL,
  `email` varchar(50) NOT NULL,
  `join_date` datetime NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

The “id” field is used as the primary key and will be the main unique identifier that we’ll use to differentiate between users in the database. The “username” is also defined as a unique key. Other fields include “password” (which will be stored after it is hashed), “email”, and “join_date” (an sql datetime variable).

Creating DB.class.php

The first class we’ll be making for this project is one to handle database operations. The goal is simple: to take the work out of using our database so that we deal with as little SQL as possible and to have data organized and returned in a easily readable format.

Here is the code, with an explanation following:

<?php
//DB.class.php

class DB {

	protected $db_name = 'yourdatabasename';
	protected $db_user = 'databaseusername';
	protected $db_pass = 'databasepassword';
	protected $db_host = 'localhost';

	//open a connection to the database. Make sure this is called
	//on every page that needs to use the database.
	public function connect() {
		$connection = mysql_connect($this->db_host, $this->db_user, $this->db_pass);
		mysql_select_db($this->db_name);

		return true;
	}

	//takes a mysql row set and returns an associative array, where the keys
	//in the array are the column names in the row set. If singleRow is set to
	//true, then it will return a single row instead of an array of rows.
	public function processRowSet($rowSet, $singleRow=false)
	{
		$resultArray = array();
		while($row = mysql_fetch_assoc($rowSet))
		{
			array_push($resultArray, $row);
		}

		if($singleRow === true)
			return $resultArray[0];

		return $resultArray;
	}

	//Select rows from the database.
	//returns a full row or rows from $table using $where as the where clause.
	//return value is an associative array with column names as keys.
	public function select($table, $where) {
		$sql = "SELECT * FROM $table WHERE $where";
		$result = mysql_query($sql);
		if(mysql_num_rows($result) == 1)
			return $this->processRowSet($result, true);

		return $this->processRowSet($result);
	}

	//Updates a current row in the database.
	//takes an array of data, where the keys in the array are the column names
	//and the values are the data that will be inserted into those columns.
	//$table is the name of the table and $where is the sql where clause.
	public function update($data, $table, $where) {
		foreach ($data as $column => $value) {
			$sql = "UPDATE $table SET $column = $value WHERE $where";
			mysql_query($sql) or die(mysql_error());
		}
		return true;
	}

	//Inserts a new row into the database.
	//takes an array of data, where the keys in the array are the column names
	//and the values are the data that will be inserted into those columns.
	//$table is the name of the table.
	public function insert($data, $table) {

		$columns = "";
		$values = "";

		foreach ($data as $column => $value) {
			$columns .= ($columns == "") ? "" : ", ";
			$columns .= $column;
			$values .= ($values == "") ? "" : ", ";
			$values .= $value;
		}

		$sql = "insert into $table ($columns) values ($values)";

		mysql_query($sql) or die(mysql_error());

		//return the ID of the user in the database.
		return mysql_insert_id();

	}

}

?>

The Code Breakdown

After the class definition you’ll see four variable declarations: $db_name, $db_user, $db_pass, and $db_host. These should be set accordingly, based on how you’ve set up your database. You’ll most likely leave $db_host as localhost. These variables are defined as “protected” and as such they will not be accessible from outside the class. From anywhere inside the class, however, they can be retrieved by using $this->db_name, $this->db_user, etc.

The first function is called connect(). This function uses those protected values to open up a database connection. This connection will remain open for usage anywhere on the current page (not just from within the class).

Here’s an usage example for this function from anywhere outside the class (pretty simple, right?):

//create and instance of the DB class
$db = new DB();

//connect to the database
$db->connect();

The second function is called processRowSet(). The purpose of this function is to take a mysql result object and convert it to an associative array, where the keys are the column names. The function loops through each row in the mysql result and the PHP function mysql_fetch_assoc() converts each row to an associative array. The row is then pushed onto an array which is ultimately returned by the function. This formatting makes the data far more readable and easier to use.

There is a second argument called $singleRow which has false as a default value. If set to true, only a single row will be returned instead of an array of rows. This is useful if you’re only expecting a single result to be returned (for example when selecting a user from the database by using their unique id).

The final three functions perform basic MySQL functions: select, insert, update. The goal of these functions is to minimalize the amount of SQL that needs to be written elsewhere in the application. Each basically builds an SQL query based upon the value passed in and executes that query. In the case of select(), the results are formatted and returned. In the case of update(), true is returned if it succeeded. In the case of insert(), the id of the newly inserted row is returned.

Here is a sample of how you might update a user in the database using the update() function:

//create an instance of the DB class
$db = new DB();

$data = array(
	"username" => "'johndoe'",
	"email" => "'johndoe@email.com'"
);

//Find the user with id = 3 in the database and update the row
//the username to johndoe and the email to johndoe@email.com
$db->update($data, 'users', 'id = 3');

As you can see, the tables column names for the columns being updated are the keys and the values are the data that is being set in those columns.

Extra Credit

Try expanding the DB class to include a function for deleting a row from the database.

Expand the select() function to take an array of column names to select with a default of * to select all columns.

What’s up next?

This wraps up part 1 of the series. We’ve managed to organize our folder/file structure for the project and build our first class, the DB class.

In part 2 we’ll build two more classes, User and UserTools. The User class will introduce class constructors. Additionally we’ll start to take a look at global.inc.php and what exactly we’ll be putting in there.

Wordpress.com stats not installed! Posted Monday, December 7th, 2009 / Back to Top

I this post. Tweet
SPONSOR

33 Comments 11 Mentions

  1. Eric B. Author Editor

    This is a very helpful tutorial. I can’t wait for the next part!

    December 7, 2009 · Reply

  2. Tanawat T. Author Editor

    Awesome! Thanks for sharing. This tutorial gave me a lot of ideas and some different approach to dev PHP app. Thanks again!

    December 7, 2009 · Reply

  3. Eric Barb Author Editor

    This is sweet! I just started playing around with PHP and this is perfect, exactly what I was looking for. When can we expect Part 2?

    December 7, 2009 · Reply

  4. Montana Flynn Author Editor

    I am really digging these style of posts, I am looking forward to the whole series.

    December 8, 2009 · Reply

  5. Orlando Author Editor

    Congratulations for the great post guys! I’m aways looking for a clear and organized php code, couldn’t been better.

    Just a question…

    The row “$db->connect();” was missing in “Update Sample” or I couldn’t understand that part.

    Thank You Guys!

    And keep the good work!

    December 8, 2009 · Reply

  6. Brian Muse Author Editor

    @Orlando
    You are absolutely correct. You would need to have opened a connection at some point before you could call update(). I was simply showing the update() usage.

    December 8, 2009 · Reply

  7. Orlando Author Editor

    @Brian Muse

    Thanks for the confirmation, thought I was kida lost in that part.

    December 8, 2009 · Reply

  8. sernan Author Editor

    i havent done some php coding lately and im very much interested on learning and reviewing stuff like these again… already followed you on twitter… nice post!

    December 9, 2009 · Reply

  9. Slobodan Kustrimovic Author Editor

    Great article. Why don’t you make him a partner :) Would love to see more PHP related articles and he’s probably very familiar with frameworks (i would love to see some tuts on CodeIgniter).

    Or else i’m gonna hire him to write on TutsValley :P

    December 9, 2009 · Reply

  10. phoebe Author Editor

    I was ready to learn php, just the need for such articles.

    December 9, 2009 · Reply

  11. Ian Author Editor

    wouldn’t it be better to open the connection in the class construct? That would save you a step that could easily be forgotten.

    December 9, 2009 · Reply

  12. Brian Muse Author Editor

    @Ian
    Your head is in the right spot, and you could certainly go about it that way. For this set of tutorials, we’ll be creating a file that will act as a bootstrap and open a database connection on every page as well as perform other necessary operations.

    If you do go about adding it to the constructor, just be aware that if you’re creating multiple instances of the DB object then mysql_connect() will be called multiple times. This shouldn’t cause a problem, though, because no new link will be established and the current link identifier will just be returned. It’s just a bit redundant.

    December 9, 2009 · Reply

  13. Ian Author Editor

    @brian muse
    I was going to mention making it a singleton, but I wasn’t sure if that was outside of the scope of the article. Making a bootstrap file the code example more clear for me. thank for the explanation. Nice job on the article!

    December 9, 2009 · Reply

  14. Ian Author Editor

    edit above ^^
    Making a bootstrap file makes the code example more clear to me

    December 9, 2009 · Reply

  15. mike Author Editor

    Awesome! I’ve just started learning oophp and this tut is very helpful. ;) Thanks and can’t wait for the next one!

    December 9, 2009 · Reply

  16. John Herren Author Editor

    I appreciate the intent of this article, but this is a good example of why PHP gets a bad rap. The code example here is vulnerable to SQL injection and is very unsafe because user input is passed directly to the query without any validation or escaping.

    Please check out the following page in the PHP manual to learn about SQL injection, or Google the term to read any of the numerous tutorials on how to safely query a database with PHP.

    http://php.net/manual/en/security.database.sql-injection.php

    December 10, 2009 · Reply

  17. Brian Muse Author Editor

    @John Herren
    Thanks for the feedback.

    Keep in mind that this tutorial is simply an introduction to making a basic application using OOP with PHP and it’s not intended for use “as-is” in a true, full-fledged web application. As such, I’ve left out sql injection avoidance among other things (no error handling either). I’m just showing the basics here.

    You are spot on though that as people further expand upon this code and become more familiar with PHP/SQL, protecting against sql injection is a must.

    There are many other resources out there that cover sql query escaping and validation. For anyone curious, you can also check out http://www.php.net/manual/en/function.mysql-real-escape-string.php

    December 10, 2009 · Reply

  18. parvez Author Editor

    Hey nice tutorial! i’ve learned many things but i’m in confused! wheres the constructor function called in this DB class?
    Thanks for great tutorial

    December 14, 2009 · Reply

  19. Austin Author Editor

    @Brian

    Yeah, I agree with you on leaving out input validation. That’s something that’s very (very) important but it can seem pointless to someone who doesn’t know a lot about SQL injection. It should definitely be something that you cover in the future.

    @parvez

    There isn’t a constructor method in this class. Not all classes have to have a constructor method.

    December 16, 2009 · Reply

  20. jex Author Editor

    isn’t this version of the update function better?

    public function update($data, $table, $where) {
    $updates = ”;

    foreach ($data as $column => $value) {
    $updates .= ($update_query === ”) ? ” : ‘, ‘;
    $updates .= $column.’ = ‘.$value;
    }

    $query = “UPDATE $table SET $updates WHERE $where;”;

    mysql_query($query) or die(mysql_error());

    return true;
    }

    I’m a beginner myself, so i don’t know.

    December 17, 2009 · Reply

  21. Majid Author Editor

    Nice work man…
    thanx alot…….

    December 21, 2009 · Reply

  22. Free Computer Tips Author Editor

    great and very helpful technique.

    December 23, 2009 · Reply

  23. Zubair Author Editor

    A great tutorial was a great help for me as an expereinced starter in php.

    December 30, 2009 · Reply

  24. Tom Author Editor

    I was wondering if you know how to delete a user using this same set of files. I have tried but I’m just a beginner.
    Many thanks.

    March 8, 2010 · Reply

  25. David Author Editor

    How can i get something out of the db?
    I tried:
    db->select(tablename, id = 3);
    and than?

    March 17, 2010 · Reply

  26. Luis Milanese Author Editor

    Excelent tutorial. :D

    March 17, 2010 · Reply

  27. MediaTech Author Editor

    Some great functions in here, thx!

    April 23, 2010 · Reply

  28. anas Author Editor

    great article

    August 18, 2010 · Reply

  29. tomm Author Editor

    This tutorial is very detailed. It has given me a few ideas on how to utilize dev PHP app for our windshield repair kit design.

    January 11, 2011 · Reply

  30. Christina Author Editor

    Tuoochdwn! That’s a really cool way of putting it!

    May 16, 2011 · Reply

  31. Joseph Author Editor

    This is really a cool tutorial. I loved surfing through it.

    December 16, 2011 · Reply

  32. personal trainer san antonio Author Editor

    Great blog and must be very helpful for my nephew who is learning PHP these day.
    I have bookmarked the link and will share it with my nephew.

    January 6, 2012 · Reply

  33. ram Author Editor

    helped

    January 10, 2012 · Reply

 

Join the Conversation

Back to Top / Comment RSS

2011 Build Internet. Created by One Mighty Roar. Icons by Komodo Media. Back to Top