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:

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:

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?):

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:

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.

Posted Monday, December 7th, 2009 · Back to Top

SPONSOR

Add Comment

82 Comments 17 Mentions

  1. Eric B. Author Editor

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

    ·

  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!

    ·

  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?

    ·

  4. Montana Flynn Author Editor

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

    ·

  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!

    ·

  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.

    ·

  7. Orlando Author Editor

    @Brian Muse

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

    ·

  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!

    ·

  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

    ·

  10. phoebe Author Editor

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

    ·

  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.

    ·

  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.

    ·

  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!

    ·

  14. Ian Author Editor

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

    ·

  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!

    ·

  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

    ·

  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

    ·

  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

    ·

  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.

    ·

    • priya Author Editor

      Constructor method is same as class name

      ·

  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.

    ·

  21. Majid Author Editor

    Nice work man…
    thanx alot…….

    ·

  22. Free Computer Tips Author Editor

    great and very helpful technique.

    ·

  23. Zubair Author Editor

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

    ·

  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.

    ·

  25. David Author Editor

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

    ·

  26. Luis Milanese Author Editor

    Excelent tutorial. :D

    ·

  27. MediaTech Author Editor

    Some great functions in here, thx!

    ·

  28. anas Author Editor

    great article

    ·

  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.

    ·

  30. Christina Author Editor

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

    ·

  31. Joseph Author Editor

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

    ·

  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.

    ·

  33. ram Author Editor

    helped

    ·

  34. KiMusubi Author Editor

    Great tutorial, really helpful.
    Thank you Brian!

    ·

  35. pushsaini Author Editor

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

    what is mean of this line ($columns .= ($columns == “”) ? “” : “, “; )

    ·

  36. Mike Author Editor

    For a site of mine I have included in this awesome script:
    – cookie based persistent login option
    – token based confirmation e-mail, and change mail address
    – modify password system
    – no users with same username or email are accepted
    – filtered registration fields (e-mail syntax verification and password strength)
    – avatar upload and management system
    – $_SESSION based live online users
    ..and so on…
    Write me if you need it!

    ·

  37. eonzerimar Author Editor

    thanks for the tutorial really informative
    already BM your site till next article

    ·

  38. smallBEE Author Editor

    I really like this tuts . so simple but it help new bee like me to understand
    how to make a web apps using php, Thanks ………..

    ·

  39. Shahbaz Ahmed Bhatti Author Editor

    i m beggine rin oops. can anybody help me please to learning oops classes. i have some problme to understan dthsi tutorial. can anybodyy help me please

    ·

  40. arun Author Editor

    hey friendz try to make IDE for PHP. like .Net so it will create more easy to develop PHP window application.

    whats up?

    ·

    • Adams Author Editor

      php is a scripting language that interacts with ur web page and the database, so creating an IDE that allows drag and drop items like VB or Java defeats its purpose

      ·

  41. buza Author Editor

    hi, this is a nice tut for people like me, beginners. Brain I would love to have this tuts in PDO. Thanks

    ·

  42. Priyank Pandey Author Editor

    This is actually what i need waiting for the second part…

    ·

  43. adrian bonningtoin Author Editor

    Do you put the SQL code on a simple HTML page?

    ·

  44. JBK Author Editor

    It would have been nice if you would have at least given some hints on how to execute the initial SQL we needed for this tutorial.

    ·

  45. Fred Author Editor

    Would have been better if it’s in mysqli as myql has been deprecated for a long long time. Great post nonetheless. I especially liked the class DB and $db->connect();

    ·

  46. Ahmed Author Editor

    This article can easily fulfill all flaws of non-experts programmers .

    ·

  47. kamna Author Editor

    please can u provide suggestions as to how to make project in a step by step manner as explained in (part 1,2,3 ) on web traffic analyser (project based on finding out how many people our your website visitors , from where they have come etc…….) using PHP ,HTML only.Its required ………….

    ·

  48. Jaywant Author Editor

    This is really a Great tutorial for every beginner .
    I loved surfing through it.
    Thanks Once again………….

    ·

  49. Twasol Author Editor

    How php will read/get this statement “UPDATE $table SET $column = $value WHERE $where” ,it’s one solid string !!

    ·

  50. John Coner Author Editor

    Thank you very much very usefull articel

    ·

  51. sudhir Author Editor

    good tutorial

    ·

  52. PHP Developer Jobs in Chandigarh Author Editor

    This is very informative and helpful. Thanks for sharing.

    ·

  53. karthik Author Editor

    it’s nice to learn in beginning stagger…

    ·

  54. bilal Author Editor

    amazing article…….i started using oops with PHP nw..thanks brian…thnx a lot

    ·

  55. Andy Author Editor

    This was exactly what I was looking for, much better than Hello World type examples and combined with http://www.phptherightway.com should really help me out. Thank you!

    ·

  56. microsoft points generator download free Author Editor

    At this time it looks like Movable Type is the top blogging platform available
    right now. (from what I’ve read) Is that what you’re using on your blog?

    ·

  57. Bob Author Editor

    hi

    ·

  58. Jamie Author Editor

    hi bob :)

    ·

  59. Bob Author Editor

    Hi jamie how r u today!!!11!1

    ·

  60. Peter Author Editor

    hi guys can i plz join your conversation

    ·

  61. Bob & Jamie Author Editor

    no peter go away

    ·

  62. Peter Author Editor

    oh okay… i have no friends :(

    ·

  63. Brian Muse Author Editor

    Can we get an admin to ban these guys above?

    ·

  64. Peter Author Editor

    Hi brian… be my friend!

    ·

  65. Brian’s Mum Author Editor

    Hi Peter, why dont u come over for some muffins later :) Brian would love to be your friend!

    ·

  66. Peter’s Dad Author Editor

    can i come too??

    ·

  67. Brian’s Father Author Editor

    only if u bring beer

    ·

  68. Bob, Jamie, Peter, Brian Muse, Peter, Brian’s Mum, Peter’s Dad, Brian’s Father Author Editor

    WE ARE ALL A HAPPY FAMILY ON THE PHP WEBSITE TUTORIAL :)

    ·

  69. ? Author Editor

    ?

    ·

  70. ! Author Editor

    …..?

    ·

  71. Spiderman Author Editor

    can someone teach me how to post comment plz. its not working

    ·

    • Spiderwoman Author Editor

      but honey u just posted one

      ·

      • Spiderman Author Editor

        shut up woman wife. u dont get a say. teach me how to post comment or i divorce u

        ·

  72. Spiderwoman Author Editor

    okz i am sik of ur crapz. i divorce u

    ·

  73. just woman Author Editor

    ok i am just woman now

    ·

  74. spiderman Author Editor

    ok gud bye

    ·

  75. single looking for love woman Author Editor

    looking for love any1!?

    ·

  76. Florin Author Editor

    This is awesome. It’s the base code and everything you need to get started with any web app. Thank you so much!

    ·

  77. raheel Author Editor

    Thanks admin,

    I would like to know that what would be the good approach

    1 – making a generic crud class as you made in this tutorial
    or
    2 – make a crud for every entity as in my case i have to crud products, categories, users, brands etc…

    ·

 

Build Internet by One Mighty Roar. Since 2008.