TechiWarehouse.Com


Top 3 Products & Services

1.
2.
3.

Dated: Aug. 12, 2004

Related Categories

PHP Programming

Introduction

Let us begin our journey into the simple yet powerful world of PHP by understanding what the term "Hypertext Pre-processor" means. Hypertext is nothing but what we commonly call "link", those strange words that take you to different places when the mouse is clicked on them. In other words Hypertext stands simply for a plain web page. Yes, I know that techi people have this queer habit of making simple things high-sounding. The term pre-processor means exactly what it says, it means that which processes before. Thus PHP processes web pages before they are sent to the browser. So a PHP page is processed first on the web-server that creates an HTML which is sent to the client, a web-browser in most cases.

I think that's already quite heavy on the newbies, let's now see who fit the eligibility criterion for this tutorial. The only basic requirement is the elementary knowledge of HTML. If you are among those who is not familiar with HTML you can read the HTML tutorial before venturing into this one. An introduction to any kind of programming would certainly help. If you are a seasoned web developer using other technologies then just read through this tutorial and with the help of the PHP manual you can add PHP into your resume.

For trying out the examples and code snippets in the following pages you will need PHP and MySQL installed and running. If you don't already have them you can download them free of cost from php.net and mysql.com. Both come with adequate installation information.

In the next section we shall look a little at the history of PHP and how it compares to the other solutions out there.

And The Rest is History...

Haven't we all heard that phrase so often, well its true for anything great and PHP is no exception to thatPHP Tutorial rule. PHP was created in 1994 by Rasmus Lerdorf to keep track of who was looking at his online resume. In 1995 the first version of PHP was released and was known as "Personal Home Page Tools" From then on PHP has grown at an enormous pace, various people have contributed to it. You can read a more detailed history of PHP in the manual or here .In a very short span of 2 years PHP became among the most widely used languages for web development. And yes, its usage is still growing at a staggering rate. There is an active community that discusses the possibilities and problems with PHP and a group of core developers that works on improving PHP and fixing bugs. You can join the PHP newsgroups at www.php.net.

Php Vs Other Technologies

There are numerous technologies available for the aspiring developer other than PHP that serve the same function as PHP, for example ASP, JSP, Perl, ColdFusion to name a few. Let me tell you that they are all good and usually its a matter of preference and the cost involved that urges the developer to pick one over the other. Opinions regarding this may vary but most PHP developers believe that PHP is easier to learn and has a superior syntax than the other languages. Additionally PHP is fast and safe. PHP is cross platform, it runs on almost anything that exists out there, naming all that PHP runs on would probably take a whole paragraph, that's why I'm omitting it. It accesses almost every existing database. And on top of all this it's FREE!! Do I need to give you more reasons why PHP has grown and has been used the way it has?

Now that we have seen what the options are and have decided to go the PHP way, let the games begin...

Let The Games Begin...

I know that you are itching to get started with hands on PHP, it has been a rather long wait but now get ready to launch yourself in the world of dynamic web-pages. When I say dynamic I mean dynamic as opposed to static; don't know the difference, well it will become clear in the next five minutes. Let us begin with two simple examples that will show us how PHP is embedded into HTML and how easy it is to create simple PHP pages. Type the following code in your favorite text editor and name the file "first.php" (remember to put quotes while naming the file otherwise it may become first.php.txt)

<html>
    <head>
        <title>My first PHP page</title>
    </head>
    <body>
<?php
  $var = "This is my first PHP page";
  echo $var;
?>
    </body>
</html>

As you can see above PHP code is put between the opening tag "<?php" and the closing tag "?>" All thats in between these two is PHP and is processed by the web-server. You will also notice that all PHP statements end with a semi-colon. Here, I should mention that in PHP we comment single line text with a double backslash "//" and multiline comment using "/*" and "*/". This will be demonstrated in the next example. Variables in PHP are always prefixed with a "$". We shall look at variables in more detail later. Now let us move on to our first page that has true dynamic content. Type in the following and name the file "greeting.php".

<html>
    <head>
        <title>good ......</title>
    </head>
    <body>
<?php
  $hour = date("H");
  if ($hour <= 11) // check if the time is before 11:00 hrs 
  {
    echo "good morning my friend";
  }
  elseif ($hour > 11 && $hour < 18)
  {
    echo "good afternoon my friend";
  }
  else
  {
    echo "good evening my friend";
  }
    /* This is a multi-line comment,     it can span over more than one line,     and go on and      on till we come to -> */
?>
    </body>
</html>

This page is truly dynamic because its results will change with the time of the day on the web-server. If the source of the output page is viewed, one sees very simple HTML code. This is because the web-server processes the PHP code before creating and sending a simple output HTML file to the browser (remember "hypertext pre-processor" well, after all its not all that stupid!!). The above script uses the PHP function date() to get the hour of the day in a 24 hour format then checks what time of the day it is and then outputs the relevant comment. It uses two of the most important concepts in programming that of variables and that of control structures. In the following page we shall have a look at these.

Variables are forever...

Maybe you are not of that opinion, but the moment you get into any kind of programming you'll see what I mean. A variable is an area of memory that is set aside to store data. In PHP you can recognize variables easily because they are prefixed with the dollar "$" sign. Variables are assigned using the assignment operator "=". Here is how it is done :

$name = "Harry Potter";
$pagenumber = 4;

Here we see that we have a variable identifier called $name and the string value "Harry Potter" has been assigned to it. Then we assign the value 4 to the variable $pagenumber. Note that we do not surround the value 4 within quotes so that PHP treats $pagenumber as a numeric value instead of a string which happens when we put quotes. Now that we have seen how variables are assigned values, let us look at the different types of variable that PHP allows :

  • String
  • Integer
  • Floating-point numbers
  • Array
  • Object

A discussion about these different types is beyond the scope of this tutorial. A detailed description and usage of each can be found in the PHP manual. Take this form me, if you want to be a good programmer then you must learn to read manuals. We shall be using variables all through this tutorial and looking at the following examples I'm sure you will get a hang of how variables are used, their function and various other important things that come by hands on coding. Now let use move on to control structures, after you have read this little bit, we shall study how PHP interacts with HTML forms and then you will have enough knowledge to create a simple game. Doesn't that sound like FUN!! Want to get there, just read how logic is implemented in programming.

NOTE : variables are case sensitive in PHP so $name is not the same as $NAME or $Name.

Control Structures

Control structures are the building blocks of any programming language. PHP provides all the control structures that you may have encountered anywhere. The syntax is the same as C or Perl, so if you are from that background you can jump to the next page where we shall see forms and PHP. Making computers think has always been the goal of the computer architect and the programmer. Using control structures computers can make simple decisions and when programmed cleverly they can do some not so simple things such as beat Gary Kasparov at chess.

if, elseif, else

We have had a look at this statement in the greeting.php example but its worth explaining this statement because it is essential to all programming. The basic If statement has the following structure:

If (a certain condition is true)
  then do something

Let's look at a simple code snippet, the following if statement checks whether the variable $textcolor has the string value "black" and if it does then displays a message saying that.

if ($textcolor == "black")
{
  echo "the color of the text is black";
}

Now say we also want to see if the text color is blue. Thus the following snippet will check for black then blue and if neither is true it will echo a message saying that the text color is neither black nor blue.

if ($textcolor == "black") 
{ 
  echo "the color of the text is black"; 
}
elseif ($textcolor == "blue")
{
  echo "the color of the text is blue";
}
else 
{
  echo "too bad!!, its neither black nor blue";
}

Say you want to now check for various colors, you could simply keep adding elseif statement. But those high-sounding techi people thought of a simpler and neater solution. Here it is :

switch

switch ($textcolor)
    {
      case "black":
        echo "I'm black";
        break;
      case "blue":
        echo "I'm blue";
        break;
      case "red":
        echo "I'm red";
        break;          
      default:    // It must be something else
        echo "too bad!!, I'm something else";
}

I'm sure an explanation is not required for the above snippet. Now let us look at other kinds of control structures those which keep doing a certain thing until a certain condition is met.

while

while (condition)
    {
      // statements
    }

Similar to if..else statements, a while loop evaluates an expression. If the condition evalutes to false, the statement inside the parentheses is skipped otherwise the code inside the braces is execured till the condition becomes false. Here is an example.

<html>
    <head>
        <title>Let us count !!!</title>
    </head>
    <body>
<?php
  $limit = 10;
  echo "<h2> Let us count from 1 to $limit </h2><br>";
  $count = 1;
  while ($count <= $limit)
  {
    echo "counting $count of $limit <br>";
    $count++;
  }
?>
    </body>
<html>

PHP offers 3 other kinds of loops - for, do..while, foreach. You should read about them in the manual. So much for the basics of the PHP programming language, now let's move on to more interactive examples that will show you just how simple PHP is.

Interactivity Keeps The Viewer Interested

Everything we have seen so far did not need any information to be entered by the user. Now we shall see how we can grab information from the viewer using HTML forms and how PHP turns this information into variables. No sense in sitting around and waiting - let's go ahead and make a web page that asks you for your name and age and displays it on another page. So we have two pages enter.htm to collect the information and result.php to process it.

<!-- enter.html -->
<html>
    <body>
   
Please enter you name and age below : <br>
<form action="result.php" method=get>
    My name is: 
    <input type="text" name="myname"><br>
    My age is:
    <input type="text" name="myage"><br><br>
    <input type = "submit" name = "submit" value ="go ahead!">
</form>
    </body>
</html>

<!-- result.php -->
<html>
    <body>
<?php
  echo "<h1>WOW $myname you are $myage years old!!!</h1>";    
?>
</body>
</html>

In the first part (enter.htm) we have in the form tag action="result.php", this basically tells the browser which page will process the resulting information. I'll come to the method=get later. Then in the next part (result.php) we have only one statement, as you can see it makes use of two variables $myname and $myage which were submitted to this page by the previous page. So it's as simple as that.

get and post

In the previous example we used the get method. Run it again and see that when the result.php loads in the address bar we have a detailed description of the variables being passed. If you want to avoid this just replace get by post in the enter.htm file. There you are, now the variables are not visible. Sometimes we may need to submit the form to itself, an obvious solution would be to put the page name in the form tag. This will work fine though it has a slight disadvantage, the name of the page can't be changed without the name being changed in the form tag too. So the guys who created PHP thought of a neater solution. We shall demonstrate this in our next example. We shall create a simple guessing game, where the computer thinks of a number between 1 and 100 and gives you hints in order to find that number.

Now The Real Game Begins

So far we have studied the PHP syntax, how to use variables and how to get information using forms now let's put all that hard work to action. Here is what we are going to make, play it a few times. Now try entering a number greater than 20 and see what happens. Cool isn't it.

<html>
    <head>
         <title>So you think you are smart huh?</title>
    </head>
	
    <body>
I have thought of a number between 1 and 20,
try your guesses<br>
<?php
  function verify($a) // a function to verify if                        // the inputs are between 1 and 20
  {
    if (($a > 20) or ($a < 1))
    { return 0; }
    else 
    { return 1; }
  }
if ($submit)
  {
    if (verify($guess))
    {
      if ($num > $guess)
      {
         echo"Not bad, but that's <b>smaller</b>              than what I thought, try again";
      }
      elseif($num < $guess)
      {
         echo"Not bad, but that's <b>greater</b>              than what I thought, try again";
      }
      else
      {
         echo"<b>WOW! you finally got it.              Care to <a href= $PHP_SELF>try again?</a></b>";
      }    
   }
    else   // bad input
    {  
      echo "Please enter a valid number!";
    }
  }
  else    // the form has not yet been submitted once,           // thus this code is executed first
{
    srand ((double) microtime()*1000000); 
    $num = rand (1, 20);
  }
?>
<form method=post action="<?php $PHP_SELF ?>">
   <input type="text" name="guess"><br>
   <input type="hidden" name=num value="<?php echo $num; ?>">
   <input type="submit" name="submit" value="check my guess">
</form>
    </body>
</html>

This example makes use of all that we have learnt and much more. Ok, i'll try to explain how the code works. Basically in the first pass over the page we generate a random number ($num) between 1 and 20. The page is submitted to itself using the $PHP_SELF variable (we could have simple used the file name instead of this variable but remember, that does not allow us to change the filename once it's created). You may be wondering how we remember the random number ($num) when the input is processed by the next instance of the page. Simple! we pass it as a hidden element. This has a very big disadvantage (I'll come to it later). The rest of the code is pretty simple apart for the fact that we define and use a function called verify.

Functions are generally pieces of reusable code or code that can be separated from the main program to make it more readable. We defined a function called verify that checks whether the value passed to it is between 1 and 20. It returns a 1 on success and a 0 on failure. If you were clever and inquisitive enough you would have seen the HTML source of the game and found out what I'm going to elaborate. When the page is sent to the browser all the PHP code is processed on the server and the output is sent as plain HTML. If you look at the source of the gameguess.php in the browser you will immediately notice that the form is sending a hidden element. And you will surely realize that it's the random number. So looking at the source you will know the random number. Imagine if that was some kind of important information like your credit card number. Don't have to be alarmed, the people who created PHP thought of that and provided facilities that solve the problem with utmost security.

Databases To The Rescue...

All right that was pretty neat for a beginner, but what would you do if you wanted to sell stuff online or maintain an online dairy where your friends entered information for you. How would you store the information? Fortunately you and I are not the first ones to think of this, in the 1960s Dr. F. F. Codd thought about what are the problems involved with storing large amount of data. He understood all the problems of various people trying to write to one database at one given time, the issues of security and much more. Finally in 1970 he published a paper "A Relational Model of Data for Large Shared Databanks." A programmer named Larry Ellison read the paper and created software that put Dr. Codds theories into practice. This software later became known as Oracle. Even today Oracle is a leading name in relational databases. And no doubt it is one of the best in the market. But Oracle is expensive and not the best database to learn on. MySQL is the answer of the open source community to databases like Oracle. Over the past few years MySQL has grown tremendously and offers most capabilities as any other database. Being open source MySQL is free, though there are some minimum charges for very specific usage. You can learn more about MySQL at www.mysql.com

We shall use MySQL to demonstrate how PHP deals with databases. Let's begin with a simple script that gets us connected to MySQL and creates a new database.

<html>
    <head></head>
    <body>
<?php
  $db = "my_database";
  $conn = mysql_connect("localhost", "root") or
    die("Count not connect to database");
  echo "connected to database.<br>";
  mysql_create_db("$db") or
    die("could not create a new database");
  echo "created database $db successfully";
?>
    </body>
</html>

If the above script does not work then you should look for typos, check with your sys admin if MySQL is running properly, and find out if you need a username, password to access it. If that is the case then you should use mysql_connect("server", "username", "password").

You may wonder that we have been able to connect, but how does one disconnect, PHP disconnects automatically when it finds the end of the script. But you may want to disconnect from MySQL before the end of the script, for that a connection variable can be defined and used to disconnect from MySQL.

<html>
    <head></head>
    <body>
<?php
  $db = "my_database";
  $conn = mysql_connect("localhost", "root") or
    die("Count not connect to database");
  echo "connected to database.<br>";
  if (mysql_close($conn))
    {
      echo "closed $db succesfully";
    }
  else
    { 
      echo "Could not close $db,             but it will close when the script ends";
    }
?>
    </body>
</html>

Creating a table in a database is as easy. We shall create a simple table that has 2 fields- name and favorite color. On the next page we shall look at a more complete example. But for now let's look at how of select a particular database once we are connected and how to make a table.

<html>
    <head></head>
    <body>
<?php
  $db = "my_database";
  // connecting to mysql
  
 $conn = mysql_connect("localhost", "root") or
    die("Count not connect to database");
  echo "connected to database.<br>";
 
 // selecting database
  mysql_select_db($db) or
    die ("Could not select database");  
  echo "selcted database $db"; 
 // creating table here
 
  $query = "create table my_table       (          name          varchar(40) null,         fav_color     varchar(40) null       )";
  
  mysql_query($query) or     die (mysql_error());
  echo "created table my_table";
 
?>
    </body>
</html>

Selecting a particular database is done with mysql_select() as shown above and the table is created by sending a query to MySQL with the mysql_query() function. If you are with me till here then you I'm sure you have enjoyed the journey so far. Next we put PHP into action with MySQL.

NOTE : In case you to delete a database called "deleteme", you could use the mysql_drop_db("deleteme") function, or in the MySQL command line client use "drop. database deleteme" or delete the mysql/data/deleteme directory.

Catering To Your Guests

Hope you have enjoyed the journey so far, let's now look at very common example, it's that of a simple guestbook. The idea is to have a page that allows the user to enter his/her name and some comments. Then we also want a page that enters the information into a database, and finally a page that displays the various comments that people have entered.

<html>
    <head>
        <title>Guestbook</title>
    </head>
    <body>
<h1> Sign my guestbook !!</h1><br>
<form action = "insert.php" method = post>
Name : &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type=text name=name><br>
Comments :
<textarea name=comments cols=30 rows=4 wrap=virtual>
</textarea>
<br><br>
<input type=submit name=submit value="Sign">
<input type=reset name=reset value="Reset">
    </body>
</html>

This (sign.htm) is a simple HTML file that takes the input from the user, the inputs are sent to insert.php for inserting into a MySQL database. Before we look into the code for insert.php, we need to create a database that will store all the data. This can be done directly using the command line client of MySQL or we can do it from PHP, the code for creating the necessary database and table is given below (create_guestbook.php):

<html>
    <head></head>
    <body>
<?php
  $db = "guestbook";
  $table = "guestbook_table";
  //  connecting to MySQL
  $conn = mysql_connect("localhost", "root") or
    die("Count not connect to database");
  echo "connected to database.<br>";
  
  //  creating database
  mysql_create_db("$db") or     die(mysql_error());
  echo "created database $db successfully.<br>";
  //  selecting database
  mysql_select_db($db) or      die ("Could not select database");  
  echo "selcted database $db.<br>";  
 
  //  creating table here
 
  $query = "create table $table       (          name          varchar(40) null,         comments      text null       )";
  
  mysql_query ($query) or      die (mysql_error());
  echo "created table my_table";
?>
    </body>
</html>

As you should have noted create_guestbook.php needs to be only run once so that the necessary database and table are created. Running it more than once will cause PHP to try and make an already existing database and will result in an error. Now that the database has been created we can go ahead and put the data in it. insert.php looks like this:

<html>
    <head>
        <title>Inserting into database</title>
    </head>
    <body>
<?php
  $db = "guestbook";
  $table = "guestbook_table";
  //  connecting to MySQL
  $conn = mysql_connect("localhost", "root") or
    die("Count not connect to database");
  echo "connected to database.<br>";
  
  //  selecting database
  mysql_select_db($db) or      die ("Could not select database");  
  echo "selcted database $db.<br>";  
 
  //  inserting info into table
  if($submit == "Sign")
  {
     $query = "insert into $table               (name, comments) values ('$name', '$comments')";
     mysql_query($query) or         die (mysql_error());
?>
<h2>Thank you!! your entry has been saved.</h2>
<h2><a href = "view_guestbook.php">View My Guestbook</a></h2>
<?php
  } // closing if ($submit == "Sign")
else
  {
?>
   
<h2>You have not yet signed my guestbook</h2>
<h2>
    <a href = "sign.htm">Sign it</a>
    <a href = "view_guestbook.php">View it</a>
</h2>
<?php
  }  // closing else
?>
    </body>
</html>

I have intentionally made so many fragments of PHP script to show you how PHP can be broken apart and HTML put in between even a simple control structure as an if..else statement. One could simple use "echo" to output all the HTML, that would make the whole file much shorter, and more readable but that's left for you to do. Simple isn't it. Now for the last part of the guestbook, we will write view_guestbook.php and you'll notice that it's even simpler than you imagined.

<html>
    <head>
        <title>Inserting into database</title>
    </head>
    <body>
<?php
  $db = "guestbook";
  $table = "guestbook_table";
  //  connecting to MySQL
  $conn = mysql_connect("localhost", "root") or
    die("Count not connect to database");
  echo "connected to database.<br>";
  
  //  selecting database
  mysql_select_db($db) or      die ("Could not select database");  
  echo "selcted database $db.<br>";  
 
  //  displaying the contents of guestbook_table
  echo "<h2>My Guestbook</h2>"; 
  $query = "select * from $table";
  $result = mysql_query($query) or      die(mysql_error());
  
  while ($row = mysql_fetch_array($result))
  {
    echo "<b>Name:</b>";
    echo $row["name"];
    echo "<br>";
    echo "<b>Comments:</b>";
    echo $row["comments"];
    echo "<br><br>";
  }
?>
<h2><a href = "sign.htm">Sign my Guestbook</a></h2>
    </body>
</html>

First we define a variable $query that is a MySQL query asking MySQL to locate all the elements in $table. We execute the query using $result=mysql_query($query). It is important to understand that mysql_query() does not return the result of a query, it opens a cursor that points to the rese table. Data is stored in the rows, so we ask MySQL to provide us with the data of each row. The function mysql_fetch_array() grabs the contents one row at a time and puts them into an array $row, which we later use to display the relevant info. mysql_fetch_array() continues to return data till none is left then it returns FALSE and we are out of the while loop.

Concluding A Beginning...

Let's begin the conclusion with what we have learnt in this brief introduction to PHP, we started our journey with an overview what PHP is, then we saw how PHP compares to other solutions. Then we saw what a dynamic page was, followed by a brief discussion on variables and control structures. Then we saw how input is taken from forms. We put all that into action in a small little guess game. Then we learnt about databases and saw a few examples of PHP with MySQL. Finally we made a simple guestbook. I would like to mention here that the examples we saw are in no way complete. Like the guestbook could do with an admin page that allows certain privileged users to moderate the content. It should verify all inputs and see to it that multiple inputs are not allowed. Nor does this tutorial cover all the aspects that a beginner needs to know, all the control structres have not been covered nor were arrays looked into. This was written to help you get a grip of PHP and to get you interested in how PHP can be used to create effective dynamic web pages.

With PHP running on more than 6 million sites, it is here to stay for sometime. So don't fell that you would be wasting your time learning an obsolete technology. Secondly once you have a grasp of any one of the server-side scripting languages changing is a matter of syntax and few rules. PHP provides a very simple environment for the beginner. So go ahead and get your hands on it. GOOD LUCK!!!

Return to the top of the page.

Now that you've gotten free know-how on this topic, try to grow your skills even faster with online video training. Then finally, put these skills to the test and make a name for yourself by offering these skills to others by becoming a freelancer. There are literally 2000+ new projects that are posted every single freakin' day, no lie!


Previous Article

Next Article


Michael's Comment
You explained this perfectly! https://bucketlist.org/idea/6LiG/ideas-to-assist-properly-deal-with-nervousness/
05 Tue Dec 2017
Admin's Reply:



John's Comment
With thanks! A good amount of stuff. https://bucketlist.org/idea/6LiG/ideas-to-assist-properly-deal-with-nervousness/
01 Fri Dec 2017
Admin's Reply:



Michael's Comment
Nicely put, Appreciate it! https://bucketlist.org/idea/6LiG/ideas-to-assist-properly-deal-with-nervousness/
20 Mon Nov 2017
Admin's Reply:



John's Comment
Seriously quite a lot of beneficial data. https://bucketlist.org/idea/6LiG/ideas-to-assist-properly-deal-with-nervousness/
18 Sat Nov 2017
Admin's Reply:



Ella's Comment
cheap authentic nhl jerseys from china; percetakancintya.com,cheap b&b new jersey
16 Tue May 2017
Admin's Reply:



Daniel's Comment
Weeeee, what a quick and easy soutlion.
09 Wed Jan 2013
Admin's Reply:

Thanks Daniel.




raaz's Comment
i want to learn asp.net,java and other programming languages are there any tutorials on this site for asp.net or c#.net or java??
07 Thu Jun 2012
Admin's Reply:

Try this one: http://www.techiwarehouse.com/engine/208feace/Java-Tutorial

But if you're like me, and not too familiar with programming, I would really suggest that you understand the fundamentals of programming first, rather than just dive into any language.




Sucheta's Comment
speechless........... @ @
09 Wed May 2012
Admin's Reply:

I hope you're speachless in a good way




Luella's Comment
I was so cnousfed about what to buy, but this makes it understandable.
15 Wed Feb 2012
Admin's Reply:

 Hi Luella

we are happy that we help you out from your problem :)




MORIS MICHAEL's Comment
what a esactry era of computer generation?
08 Tue Mar 2011
Admin's Reply:

esactry era ?




Rajesh's Comment
I am a beginner in php learning so I need some help in easy way for learning PHP
15 Sat Jan 2011
Admin's Reply:

Well you're in the right place.




Sotey_Toeurm's Comment
I want to learn more of PHP and MySQL and Database Online.
17 Fri Dec 2010
Admin's Reply:

See if this helps you more: Building Dynamic Web Pages with PHP






Facebook