Beginners guide to advanced webcoding
Therefor I decided to write a detailed post about PHP coding which will explain what is exactly is, how it works and what you can do with it.
Don’t get me wrong, I agree, at first glance this will be somewhat confusing. But if you spend an hour or 2 practicing and playing around with it, you’ll be well on your way. Once you get the idea and the way of thinking, it really is not such a big deal.
And it is true, you can create some very complex scripts with PHP, but you can do the exact same with a simple language like In any case, I can only encourage you to try this, step by step.
Start with something small, make sure you understand what happens and before you know it, you are creating complete and fool proof websites.
Brace yourselves, this will be a rather large post, since I need to go into detail for you to understand the context of this language and the use of it. But before we start, I cannot stress enough that literally EVERYONE can learn how to write PHP. Trust me, it’s really not such a big deal.
For starters, in order to start coding PHP you will always need following 3 components:
- PHP: the actual language. With this language you can dynamically generate HTML pages. This simply means that the content of a webpage can differ based on what the end user requests. Or, based on the user that has logged in, different items will be shown.
A great example is a shopping basket of a webshop. I can’t see which products you purchased. Nor can you see what I purchased. This is because the webpage is dynamically build for our user.One of the big differences between PHP and HTML is that PHP is a server side scripting language. Unlike HTML, which is rendered on the client side. Why do I say that it is a server side scripting language? Simple, the PHP code you wrote has to be read and processed by a web server (we’ll get to that) with a PHP processor (something that read and understand PHP). This web server does all the “things” you “described” in your code.
The result will be an HTML page, the end user can never see which PHP code you actually used to build the website since the code has been processed and translated to HTML.PHP can be used on most platforms and it free of costs. How great is that, your personal, free of license, website toolkit.
Are there any other server side scripting languages? Ofcourse, lots of them, the most known competitor is ASP from Microsoft. This technology is, however, not free of charge.
- Web server: consider a web server as a translator. You speak a foreign language that has to be translated to something everyone can understand. This is the task of the web server, reading and understanding the scripts you wrote. You should know that a web server is not only used for running PHP pages, but it can be used for a lot of other things as well.
Applications can be deployed on a web server so it can fulfill your technical needs. Now in order to run and understand PHP pages a PHP, let’s call it, module should be installed. Consider this the dictionary the web server uses to translate the pages you offer. For PHP, typically the apache webserver is used (again, there are many web servers out there, PHP can be used on most of them).
- Database: Since you are going to create a website that allows a user to query, store and edit data, you’ll need a place where you can stock all of this information. The ideal place to do this, is ofcourse a database. Mostly a MySql database is used for PHP application. But again, you can use most types of databases. As long as a connector exists for this type of database. I won’t go too much into detail here since I already wrote a post about it which you can find here.
This is probably the hardest part if you want to write PHP scripts that interact with a database. Because you will also have to write some SQL code. This is the language you use to “ask questions” to the database. Sadly enough, the database cannot interprete plain PHP code. It works a little different. But again, don’t let this stop you. SQL is by far the easiest type of language around. Very easy to read as well. I wrote some stuff about this as well here (what’s it called? Oh right! Too much spare time).
Good, this is the cocktail you need for your PHP application. It looks mindblowing I know, because you have to start looking for a webserver and a database and on top of that you also have to learn scripting all those things.
Well, not exactly.. As I promised, this guide will be to show you that it really is not that hard.
If you want to start developing on a windows machine for example (which I presume is still most commonly used) you can download a little tool that does all the setup for you!
It’s called WAMP. It’s free and it really is light. This toolkit contains an apache web server, mysql database and everything you need to start scripting PHP. It take literally 5 minutes to install. A quick recap, WAMP stands for Windows Apache Mysql and PHP. Like this you can use your computer to start creating your website. Even to start hosting your own website, but we’ll get to that later on. As I said. Step by step.
If you are using Linux, you can’t use WAMP, obviously. A great alternative exists… 3 guesses?.. Indeed LAMP.
This doesn’t come (at least not that I know of) in an executable package. You will need to download every package seperatly. I think you can easly do this with YUM or APT-GET. And else you can download all RPMs from the corresponding websites.
A real nice guide on how to install a LAMP can be found here (not written by me for a change..). Since you are a linux user, I assume that you are a more advanced user. So that shouldn’t be a problem :).
Alright, so far so good. We now got everything we need:
- Web server: Apache –> Check!
- Database: MySQL –> Check!
- PHP plugins: wamP –> Check!
- Sharp’s Guide: yeah babeh –> Check!
- The force: with you –> Check!
Time to start coding! In order to make your coding life a lot easier, download and install NOTEPAD++. This is an optional step. If you really don’t want to do this then just skip this.
But let me quickly explain why I prefer to use notepad++. This is an advanced version of the notepad that is installed by default on virtually every computer. And one of the great features of this tool is that it can recognise program languages.
So if you start coding HTML for example, it will format your code, so it is easier to debug or easier to see where something should be added in your code.
I wrote a small HTML script just to show you:
You see, all containertags are marked in blue, the options in red and the comments in green. Mind that this will change nothing to your code. It really is there to make your life easier.
Not will this tool validate your code. If there is something wrong in there, too bad, but you’ll have to remove it manually :).
Let’s test if everything works like it should work. Startup WAMP and if it isn’t done automatically, start up all the services. You do this by just clicking the W icon next to the windows clock and pick the option “Start all services”. The W should be green, this means everything is running.
Next navigate to http://localhost. You should now see a page with a title that says “Server Configuration”. This is a PHP page that shows which extensions are loaded and some links to tools. You can ignore most of it.
Now before we start doing anything else, let’s create the database where we can store our data. There are a lot of ways to do this. You can either do it with the command line or with a tool. And since WAMP is delivered with a web based tool called PHP buddy, we will use this to create a database.
This will make it a lot easier on you, specially if it’s the first time that you create a mysql database.
So, from the localhost index page which you’ve just opened, click the link SQLBUDDY below Your Aliases.
You’ll be redirected to a login page. This will log you in to the actual MySql “server”. Some default values are already filled out, like the type of connection, host and user name. Leave everything by default, even the blank password. And click login.
There we are, you are now logged in. How hard was that? ;-).
Now on the first page you see, there is a big title that says CREATE A NEW DATABASE. Wonder what that does? :D
Alright, let’s create the database, enter a name a pick a charset. I picked UTF8. Oh no! More strange words. Nope, this is very simple as well. A charset is simply the character set of the database. The most commonly used is latin1 for a mysql database. This contains the characters we’ll used most.. Like the letters of our alphabet and the most commonly used punctuations. UTF8 on the other hand is more expanded. This character set also contains special characters which I may be needing.
There are tons of characters sets available, if you want to know the details about a specific one, just google it. It really is easy to find. But for now, this is all you need to know about it.
Once you entered this information, click the submit button.
The next screen will allow you to alter the database and allow you to add tables. And you will probably hate me for this now, but I’m going to show you how to create tables by using the command line. So with SQL… The reason for this is simple. You will be needing SQL coding in your PHP script anyway, so you may as well get used to it.
First a small recap, tables are database objects that will contain data in a structured way.
A table consists of rows and columns. One row of data in a table is called a record.
Got it? Okay, let’s create our first table.
Click on the W icon next to the windows clock, select the MySql option and open up the MySql console. A dos prompt will open and it will say: Enter Password.
This is the same password you just used to log in to sqlbuddy. Meaning, just hit enter, since there is not password for the root user, unless you’ve just changed it :).
Once you did this, some information will come up which you can completely ignore, do note that you can type in this window.
We can now process SQL statements since we are connected to the mysql server.
Alright, let’s create our first table. Before you can do that, you’ll need to select the correct database first. That’s a very simple command. Type use <name of the database> and hit enter.
The terminal will now state that you switched databases:
Just to be clear, my database is called DEMO… For obvious reasons. Right, now you are using the correct database. So let’s type the code for the table we will be creating. Let’s create a table with the name PERSON. We will be storing a name, first name and a unique ID for each person.
This unique ID will be used in other tables to refer to the PERSON table. Like this you only have to store data once in each table. And since the ID has to be unique at all times, we can best let this ID be generated automatically.
There is a very easy way to do this, in the database you can define a sequence. This is just a series of numbers that is increased by a certain number each time it is used.
For the code. Enter following lines to create the table. Then hit enter.
CREATE TABLE PERSON
ID INT PRIMARY KEY AUTO_INCREMENT,
When you hit enter, the database will tell you Query OK, 0 rows affected (0.06 sec).
Let me quickly explain what the commands you just entered mean. It really is fairly simple.
First of all you will need to tell the database you will be creating a table, you do this by just typing
CREATE TABLE <table name>
Pretty straight forward… Next you will need to define the columns. All column definitions should be between brackets. So before you start entering the definitions, type a ( .
The column definitions are also very easy, you can use the same basic syntax for each and every column you will ever use.
There are 2 things a column definition always needs, those are a name and a datatype.
So the format will always be:
But as you already noticed. My ID column has more than just a name and a definition. This is because there are a few optional options. For example, the unique ID I told you about will be the PRIMARY KEY of this table. A primary key is nothing more than what I’ve just told you. A field that contains a unique value in this particular table. A primary key can also be a combination of fields in the table. But let’s keep that for another time shall we? :).
Another thing you see in the column definition of ID is AUTO_INCREMENT this is the sequence we discussed. If you enter this option for a specific column the database will initialize a sequence that will automatically enter a number in this column, each time increased by 1
These additional options are called CONSTRAINTS, because the “limit” the use of a field in a specific table. All datatype definitions available in mysql can be found here and here is more information about the create table statement and the available constraints.
The datatype for my ID column is INT, which obviously stands for INTEGER. So to make a long story short, the definition for my ID column is:
ID INT PRIMARY KEY AUTO_INCREMENT
The second column is easier. But before you start typing the second definition, mind the , after the first definition. Each column definition should be seperated by a , . You’ll get an error if you don’t do this.
My name column has nothing special, the type for this column is VARCHAR(100), a commonly used type for storing strings (… har har har… this just means a series of characters). The 100 just indicated how many characters this field can contain. In this case 100 characters :).
So the definition of the name column is:
The same goes for the FST_NAME column. Again, don’t forget your comma after the previous field.
When you are done defining all the columns of your table, close the brackets by just entering ).
If you now hit enter, you’ll notice that nothing happens. That’s normal, SQL should be ended with a ; . Like this you indicate that the command is now complete.
Do this and hit enter, the prompt will now tell you if the command is OK or not.
Right so now we’ve got an empty table. I’ll quickly show you how to add a line in your table. Just for fun. Enter following line:
INSERT INTO PERSON VALUES (NULL, ‘BLOG’,’SHARP’);
The output will be something like:
RIght, the insert statement is also very simple. You tell the database INSERT INTO PERSON VALUES, which just means, add following values in the table PERSON. The values are entered between, again, brackets separated by columns. Values should be added in the same order as you added them to the table. So in this case the order is ID, NAME, FST_NAME. Notice the NULL as first value.
NULL means nothing in a database. So we will enter an empty value as ID. The reason for this, is rather obvious. Remember that we defined the ID column with the option AUTO_INCREMENT, so the database will enter a value automatically. But, the insert statement will be invalid if you enter less values than there are columns. So in stead of entering a value, we just pass along nothing.
The next value is the NAME, values of datatype data, datetime, string and char (and I few others that don’t pop in my mind right now) should be put between single quotes. So I entered the value ‘BLOG’. The same goes for the FST_NAME. Don’t forget the commas, and the “close” bracket. At the end of the command just put a semicolon again and hit enter.
Select now view the data in the table. We do this with a select statement. This is a statement you will be using quite a lot when scripting PHP. Mostly to generate dynamic webpages. A select statement has 2 required options and 4 optional options. The 2 required ones should tell the database what it should get and where it should be retrieved from. Basically this means which columns from which tables.
You can also put filters in your query and an order with the WITH and ORDER BY clause. Also available are the HAVING and the GROUP BY option. Which I won’t discuss right know, since they won’t be needed right now.
The syntax of a select statement should always be in this order:
So let’s make the database clear that we want to see all DATA, from all COLUMNS from TABLE PERSON.
SELECT ID, NAME, FST_NAME
If you run this query the result will be :
There is a shorter alternative though. Since we want to see all columns from the table anyway, we can replace all the column names with an asteriks. The query will look like this:
The result will be identical:
Alright.. Not much of a big deal is it? Now in our PHP script we will need to connect to the database. So I think in this case it’s the best if we create a new database user. Since ROOT is really the superuser of the database server and we don’t want this account to fall in the wrong hands.
We’ll do this as well with SQL buddy. So open this up again, by now you know how ;-). In the left hand column click on the USERS link. Because we’ll be creating… indeed.
Fill in the fields as followed and hit SUBMIT:
Okay, now you got yourself a new user. Do take a note of the password, you’ll be needing it in an instant.
For the next step, open up notepad++ or whatever tool you will be using to write your HTML/PHP script.
As an example let’s create a small webpage with 2 functionalities, Adding a person and selecting all persons.
Let’s write the select page first because this will be the most complex. Don’t worry it still is rather easy.
This is the template I wrote we’ll be using in this tutorial.
Do notice that nothing PHP like is written in this file so far. I want to show a list of names and first names of all people in the PERSON table. And I’ll be doing this in a table. The reason for this is that it is easier to position all the data you want to make visible.
As you may remember an HTML table consist of following tags
- <TABLE>: this will initialize a table
- <TR>: this will create a new row in the table (this is basically the same as a database table)
- <TH>: this creates a table heading, the data in this tag will be printed in bold
- <TD>: this creates a new table cell
We can already create the table and TH tags, but all the other tags will be initialized by the PHP script. Since we don’t know how many persons will be in the table we have to other choice than to do it like this.
The script with the table table looks like this. Notice that I entered the option border=1, this just puts a black border around the cells in the table.
The action PHP script needs to be put between the TABLE tags and below the TH and TR tags.
It will look something like this:
Looks a bit complex at first but it’s simple. All your PHP code comes within the PHP tag. This tag is initialized by <?PHP and ends with ?> … Always! If you see something like $somename this means that a variable is intialized. A variable is a value that hasn’t been defined yet. Or a value that is initialized and that can be used throughout your entire script. So you don’t have to type the entire code every time you want to use it. You can use the variable as a substitution.
As you can see there are 4 variables in this script (you can do with less, but this makes is somewhat easier to explain).
The first one is the variable $con, this variable contains a PHP function that allows you to connect to the database. This is the MYSQL_CONNECT variable. In order to allow this function to connect you to the database it needs some information. It needs the machinename or IP address where the mysql database is located, the username and the password. In my example this is:
So the machine name is localhost the user is SHARP as so is the password (yes you can obscure the password but let’s not go there right now). So the variable $con just contains this information.
Very important in PHP is that you put a semicolon after each PHP statement you make. Same story as with SQL, this just indicated the command had ended.
There are a few exceptions, loops and if clauses for example shouldn’t get a semicolon, but then again, the code you define IN the loop should be ended with a semicolon.
Speaking of an IF clause. This is next up in the code. IF checks for a condition, in this case, it checks if the connection fails. The exclamation point says NOT. So, If NOT (returns false) $CON then write a message to the webpage.
This message is retrieve by a function as well, 2 actually:
die(‘Could not connect: ‘ . mysql_error())
The die function stops and exits the script. The text between single quotes is a static text and it is concatinated (the . will make sure the text is concatenated with whatever that follows) by the mysql error that is raised. This is what the MYSQL_ERROR() function does. It shows the error that the database returns.
As you remember, in the mysql console you had to select the correct database to start working. You’ll need to do the same in the PHP script. The next function in the script takes care of that.
This function requires 2 parameters, the first is the name of the database (and yes you need to put this between double quotes, same as with the connect function) and the connection you will be using. And since we put this information in a variable, we can just enter the variable $con. Handy.. isn’t it?
Since we want to retrieve data from the database and in specific our PERSON table we need to write and send a SQL to the database. So I decided to put this query in a variable as well. Variable name is obviously $query (just to be clear, you can name your variables whatever you want). The query is also a string in this case so between double quotes I put the query that we also used earlier.
$query = “select * from PERSON”
The next variable contains the result, I kinda gave it away by the name didn’t I? This variable contains a function that will send a query to the database. So this function requires 1 parameter, a query. The one we just put in the $query variable.
So the line will look something like this:
Now the actual work begins, all the preparation has been done.
while( $array = mysql_fetch_assoc($result))
This is called a while loop, and it’s function is to do something for as long as the condition is true. In the condition you see that a new variable is used, $array. This is the variable where the actual data from the query will be parsed to. Each time the script goes trough the while loop a new line will be put in the $array variable for as long as there is data in the resultset. There is a function used in order to get this done, this function requires one parameter, to be exact the dataset which you’ve just initialized.
What happens in the while loop is nothing more than printing data to the HTML document. ECHO means that something will be printed and as you can see that for each line in the resultset we will print TR and TD tags. So for each line this will be entered. This makes the HTML files dynamically.
A word of explanation for the echo “$array[NAME]” line. This means print the value NAME from the $array variable. The NAME value comes from the query. As you know we created a PERSON table with the columns ID, NAME, and FST_NAME.
So the value for name will be printed for each and every line. Same story for the FST_NAME.
We’re almost there now. All that is left is to close the mysql connection we opened. This can be done easly with the function mysql_close($con). This just says CLOSE the connection you find in variable $CON.
Close the PHP tag and done!
You have to save the file in a specific location. In the root folder where you installed WAMP, you’ll find a folder which is called WWW. The file should be saved here and the extension should be .PHP. Else the server doesn’t know this script should be parsed. I saved the file with the name DEMO.php.
The result of this script will look like this (you can reach this page from http://localhost/DEMO.php):
Let’s build the insert page now. Pages actually, it cannot be done in 1 step. You first will need to create a page that contains a form which allows you to enter the NAME and the FST_NAME. The second page is the actual PHP page which will send the information from the form to the database with an insert script (and that’s why I told you how to write an insert statement).
I’m not going to explain the entire form, since I’m pretty sure that by now you already know how to do this. My code looks like this:
Nothing special besides the action of the form. When you press the submit button (bottom of the table), the script insertPerson.PHP will be called. True, this doesn’t exists yet. We’ll be creating this now.
Notice that I gave the option NAME to both TD tags. This is because we will be needing these names to define the data we will push to the PHP script.
By the way this page can be saved as HTML since no PHP is present and nothing needs to be parsed.
My PHP script looks like this. Notice that I didn’t even bother to put it between HTML tags (this post is already long enough as it is). Most of the syntax is the same as before:
Again the connection, checking if the connection fails, selecting the database. And the SQL statement is different, obviously this is now an insert statement. This insert statement is between double quotes and the same as the one we created earlier in this post. It also contains 3 values, the first is NULL (you remember why). The next 2 are the values we received from the previous page, we had 2 fields there, one with the name .. erh.. NAME and one with FST_NAME. If we want to use the values that have been send from this form we have to use the syntax $_POST[name of the value]. Note that this put between single quotes, this is because this is an SQL statement and string should be put between single quotes!
And that’s it basically, the next IF clause just checks if the query is correct and if it returns errors. When something is wrong it will be printed to the screen. When the statement has been processed correctly the line 1 record added will be printed.
Save this file as insertPerson.PHP, again like the 2 previous files in the WWW folder.
Alright, let’s give it a test drive:
This one is reachable from http://localhost/insertperson.html (in my case at least).
When I hit create:
Now, just for fun, open the select page again (in my case http://localhost/demo.php):
Right, this was one of the most epic posts I ever wrote and it took me 3 days to complete it.
I really hope you have a better understanding of PHP now and you are eager to learn more :).
if you have any questions I’ll be more than glad to help you out.