Wednesday 11 July 2012

PHP Statements wit example Tutorial


If Statement
The PHP if statement is very similar to other programming languages use of the if statement, but for those who are not familiar with it, picture the following:
Think about the decisions you make before you go to sleep. If you have something to do the next day, say go to work, school, or an appointment, then you will set your alarm clock to wake you up. Otherwise, you will sleep in as long as you like!
This simple kind of if/then statement is very common in every day life and also appears in programming quite often. Whenever you want to make a decision given that something is true (you have something to do tomorrow) and be sure that you take the appropriate action, you are using an if/then relationship.
The PHP If Statement
The if statement is necessary for most programming, thus it is important in PHP. Imagine that on January 1st you want to print out "Happy New Year!" at the top of your personal web page. With the use of PHP if statements you could have this process automated, months in advance, occuring every year on January 1st.
This idea of planning for future events is something you would never have had the opportunity of doing if you had just stuck with HTML.
If Statement Example
The "Happy New Year" example would be a little difficult for you to do right now, so let us instead start off with the basics of the if statement. The PHP if statement tests to see if a value is true, and if it is a segment of code will be executed. See the example below for the form of a PHP if statement.
PHP Code:
$my_name = "someguy";
if ( $my_name == "someguy" ) {
echo "Your name is someguy!
";
}
echo "Welcome to my homepage!";
Display:
Your name is someguy! Welcome to my homepage!
Did you get that we were comparing the variable $my_name with "someguy" to see if they were equal? In PHP you use the double equal sign (==) to compare values. Additionally, notice that because the if statement turned out to be true, the code segment was executed, printing out "Your name is someguy!". Let's go a bit more in-depth into this example to iron out the details.
• We first set the variable $my_name equal to "someguy".
• We next used a PHP if statement to check if the value contained in the variable $my_name was equal to "someguy"
• The comparison between $my_name and "someguy" was done with a double equal sign "==", not a single equals"="! A single equals is for assigning a value to a variable, while a double equals is for checking if things are equal.
• Translated into english the PHP statement ( $my_name == "someguy" ) is ( $my_name is equal to "someguy" ).
• $my_name is indeed equal to "someguy" so the echo statement is executed.
A False If Statement
Let us now see what happens when a PHP if statement is not true, in other words, false. Say that we changed the above example to:
PHP Code:
$my_name = "anotherguy";
if ( $my_name == "someguy" ) {
echo "Your name is someguy!
";
}
echo "Welcome to my homepage!";
Display:
Welcome to my homepage!
Here the variable contained the value "anotherguy", which is not equal to "someguy". The if statement evaluated to false, so the code segment of the if statement was not executed. When used properly, the if statement is a powerful tool to have in your programming arsenal!
If/Else Conditional Statment
Has someone ever told you, "if you work hard, then you will succeed"? And what happens if you do not work hard? Well, you fail! This is an example of an if/else conditional statement.
• If you work hard then you will succeed.
• Else, if you do not work hard, then you will fail.
How does this translate into something useful for PHP developers? Well consider this:
Someone comes to your website and you want to ask this visitor her name if it is her first time coming to your site. With an if statement this is easy. Simply have a conditional statement to check, "are you visiting for the first time". If the condition is true, then take them to the "Insert Your Name" page, else let her view the website as normal because you have already asked her for her name in the past.
If/Else an Example
Using these conditional statements can add a new layers of "cool" to your website. Here's the basic form of an if/else statement in PHP.
PHP Code:
$number_three = 3;
if ( $number_three == 3 ) {
echo "The if statement evaluated to true";
} else {
echo "The if statement evaluated to false";
}
Display:
The if statement evaluated to true
This is a lot to digest in one sitting, so let us step through the code, line by line.
• We first made a PHP variable called $number_three and set it equal to 3.
• In this example we compared a variable to an integer value. To do such a comparison we use "==", which in English means "Is Equal To".
• $number_three is indeed Equal To 3 and so this statement will evaluate to true.
• All code that is contained between the opening curly brace "{" that follows the if statement and the closing curly brace "}" will be executed when the if statement is true.
• The code contained within the else segment will not used.
Execute Else Code with False
On the other hand, if the if statement was false, then the code contained in the else segment would have been executed. Note that the code within the if and else cannot both be executed, as the if statement cannot evaluate to both true and false at one time! Here is what would happen if we changed to $number_three to anything besides the number 3.
PHP Code:
$number_three = 421;
if ( $number_three == 3 ) {
echo "The if statement evaluated to true";
} else {
echo "The if statement evaluated to false";
}
Display:
The if statement evaluated to false
The variable was set to 421, which is not equal to 3 and the if statement was false. As you can see, the code segment contained within the else was used in this case.
PHP - Elseif
An if/else statement is great if you only need to check for one condition. However, what would you do if you wanted to check if your $employee variable was the company owner Bob, the Vice President Ms. Tanner, or a regular employee? To check for these different conditions you would need the elseif statement.
PHP - Elseif What is it?
An if statement is made up of the keyword "if" and a conditional statement (i.e. $name == "Ted"). Just like an if statement, an elseif statement also contains a conditional statement, but it must be preceded by an if statement. You cannot have an elseif statement without first having an if statement.
When PHP evaluates your If...elseif...else statement it will first see if the If statement is true. If that tests comes out false it will then check the first elseif statement. If that is false it will either check the next elseif statement, or if there are no more elseif statements, it will evaluate the else segment, if one exists (I don't think I've ever used the word "if" so much in my entire life!). Let's take a look at a real world example.
PHP - Using Elseif with If...Else
Let's start out with the base case. Imagine we have a simpler version of the problem described above. We simply want to find out if the employee is the Vice President Ms. Tanner. We only need an if else statement for this part of the example.
PHP Code:
$employee = "Bob";
if($employee == "Ms. Tanner"){
echo "Hello Ma'am";
} else {
echo "Morning";
}
Now, if we wanted to also check to see if the big boss Bob was the employee we need to insert an elseif clause.
PHP Code:
$employee = "Bob";
if($employee == "Ms. Tanner"){
echo "Hello Ma'am";
} elseif($employee == "Bob"){
echo "Good Morning Sir!";
}else {
echo "Morning";
}
Display:
Good Morning Sir!
PHP first checked to see if $employee was equal to "Ms. Tanner", which evaluated to false. Next, PHP checked the first elseif statement. $employee did in fact equal "Bob" so the phrase "Good Morning Sir!" was printed out. If we wanted to check for more employee names we could insert more elseif statements!
Remember that an elseif statement cannot be used unless it is preceded by an if statement!
PHP Switch Statement
In the previous lessons we covered the various elements that make up an If Statement in PHP. However, there are times when an if statement is not the most efficient way to check for certain conditions.
For example we might have a variable that stores travel destinations and you want to pack according to this destination variable. In this example you might have 20 different locations that you would have to check with a nasty long block of If/ElseIf/ElseIf/ElseIf/... statements. This doesn't sound like much fun to code, let's see if we can do something different.
PHP Switch Statement: Speedy Checking
With the use of the switch statement you can check for all these conditions at once, and the great thing is that it is actually more efficient programming to do this. A true win-win situation!
The way the Switch statement works is it takes a single variable as input and then checks it against all the different cases you set up for that switch statement. Instead of having to check that variable one at a time, as it goes through a bunch of If Statements, the Switch statement only has to check one time.
PHP Switch Statement Example
In our example the single variable will be $destination and the cases will be: Las Vegas, Amsterdam, Egypt, Tokyo, and the Caribbean Islands.
PHP Code:
$destination = "Tokyo";
echo "Traveling to $destination
";
switch ($destination){
case "Las Vegas":
echo "Bring an extra $500";
break;
case "Amsterdam":
echo "Bring an open mind";
break;
case "Egypt":
echo "Bring 15 bottles of SPF 50 Sunscreen";
break;
case "Tokyo":
echo "Bring lots of money";
break;
case "Caribbean Islands":
echo "Bring a swimsuit";
break;
}
Display:
Traveling to Tokyo Bring lots of money
The value of $destination was Tokyo, so when PHP performed the switch operating on $destination in immediately did a search for a case with the value of "Tokyo". It found it and proceeded to execute the code that existed within that segment.
You might have noticed how each case contains a break; at the end of its code area. This break prevents the other cases from being executed. If the above example did not have any break statements then all the cases that follow Tokyo would have been executed as well. Use this knowledge to enhance the power of your switch statements!
The form of the switch statement is rather unique, so spend some time reviewing it before moving on. Note: Beginning programmers should always include the break; to avoid any unnecessary confusion.
PHP Switch Statement: Default Case
You may have noticed the lack of a place for code when the variable doesn't match our condition. The if statement has the else clause and the switch statement has the default case.
It's usually a good idea to always include the default case in all your switch statements. Below is a variation of our example that will result in none of the cases being used causing our switch statement to fall back and use the default case. Note: there is no case before default.
PHP Code:
$destination = "New York";
echo "Traveling to $destination
";
switch ($destination){
case "Las Vegas":
echo "Bring an extra $500";
break;
case "Amsterdam":
echo "Bring an open mind";
break;
case "Egypt":
echo "Bring 15 bottles of SPF 50 Sunscreen";
break;
case "Tokyo":
echo "Bring lots of money";
break;
case "Caribbean Islands":
echo "Bring a swimsuit";
break;
default:
echo "Bring lots of underwear!";
break;
}
Display:
Traveling to New York Bring lots of underwear!
Using PHP With HTML Forms
It is time to apply the knowledge you have obtained thus far and put it to real use. A very common application of PHP is to have an HTML form gather information from a website's visitor and then use PHP to do process that information. In this lesson we will simulate a small business's website that is implementing a very simple order form.
Imagine we are an art supply store that sells brushes, paint, and erasers. To gather order information from our prospective customers we will have to make a page with an HTML form to gather the customer's order.
Note: This is an oversimplified example to educate you how to use PHP to process HTML form information. This example is not intended nor advised to be used on a real business website.
Creating the HTML Form
If you need a refresher on how to properly make an HTML form, check out the HTML Form Lesson before continuing on.
We first create an HTML form that will let our customer choose what they would like to purchase. This file should be saved as "order.html"
.
order.html Code:


Tizag Art Supply Order Form





Quantity:



Display:
Tizag Art Supply Order Form PaintQuantity: Submit Query
Remember to review HTML Forms if you do not understand any of the above HTML code. Next we must alter our HTML form to specify the PHP page we wish to send this information to. Also, we set the method to "post".
order.html Code:


Tizag Art Supply Order Form





Quantity:



Now that our "order.html" is complete, let us continue on and create the "process.php" file which will process the HTML form information.
PHP Form Processor
We want to get the "item" and "quantity" inputs that we have specified in our HTML form. Using an associate array (this term is explained in the array lesson), we can get this information from the $_POST associative array.
The proper way to get this information would be to create two new variables, $item and $quantity and set them equal to the values that have been "posted". The name of this file is "process.php".
process.php Code:


$quantity = $_POST['quantity'];
$item = $_POST['item'];
echo "You ordered ". $quantity . " " . $item . ".
";
echo "Thank you for ordering from Tizag Art Supplies!";
?>

As you probably noticed, the name in $_POST['name'] corresponds to the name that we specified in our HTML form.
Now try uploading the "order.html" and "process.php" files to a PHP enabled server and test them out. If someone selected the item brushes and specified a quantity of 6, then the following would be displayed on "process.php":
process.php Code:
You ordered 6 brushes.
Thank you for ordering from Tizag Art Supplies!
PHP & HTML Form Review
A lot of things were going on in this example. Let us step through it to be sure you understand what was going on.
1. We first created an HTML form "order.html" that had two input fields specified, "item" and "quantity".
2. We added two attributes to the form tag to point to "process.php" and set the method to "post".
3. We had "process.php" get the information that was posted by setting new variables equal to the values in the $_POST associative array.
4. We used the PHP echo function to output the customers order.
Remember, this lesson is only to teach you how to use PHP to get information from HTML forms. The example on this page should not be used for a real business.

PHP Include Function with example Tutorial


Include Function
Without understanding much about the details of PHP, you can save yourself a great deal of time with the use of the PHP include function. The include function takes a file name and simply inserts that file's contents into the script that calls used the include function.
Why is this a cool thing? Well, first of all, this means that you can type up a common header or menu file that you want all your web pages to include. When you add a new page to your site, instead of having to update the links on several web pages, you can simply change the Menu file.
An Include Example
Say we wanted to create a common menu file that all our pages will use. A common practice for naming files that are to be included is to use the ".php" extension. Since we want to create a common menu let's save it as "menu.php".
menu.php Code:


Home -
About Us -
Links -
Contact Us
Save the above file as "menu.php". Now create a new file, "index.php" in the same directory as "menu.php". Here we will take advantage of the include function to add our common menu.
index.php Code:


This is my home page that uses a common menu to save me time when I add
new pages to my website!



Display:
Home - About Us - Links - Contact Us
This is my home page that uses a common menu to save me time when I add new pages to my website!
And we would do the same thing for "about.php", "links.php", and "contact.php". Just think how terrible it would be if you had 15 or more pages with a common menu and you decided to add another web page to that site. You would have to go in an manually edit every single file to add this new page, but with include files you simply have to change "menu.php" and all your problems are solved. Avoid such troublesome occasions with a simple include file.
What do Visitors See?
If we were to use the include function to include a common menu on each of our web pages, what would the visitor see if they viewed the source of "index.php"? Well, because the include function is pretty much the same as copying and pasting, the visitors would see:
View Source of index.php to a Visitor:


Home -
About Us -
Links -
Contact Us

This is my home page that uses a common menu to save me time when I add
new pages to my website!



The visitor would actually see all the HTML code as one long line of HTML code, because we have not inserted any new line characters. We did some formatting above to make it easier to read. We will be discussing new line characters later.
Include Recap
The include command simply takes all the text that exists in the specified file and copies it into the file that uses the include function. Include is quite useful when you want to include the same PHP, HTML, or text segment on multiple pages of a website. The include function is used widely by PHP web developers.
The next lesson will talk about a slight variation of the include function: the require function. It is often best to use the require function instead of the include function in your PHP Code. Read the next lesson to find out why!
PHP Require Function
Just like the previous lesson, the require function is used to include a file into your PHP code. However there is one huge difference between the two functions, though it might not seem that big of a deal.
Require vs Include
When you include a file with the include function and PHP cannot find it you will see an error message like the following:
PHP Code:

include("noFileExistsHere.php");
echo "Hello World!";
?>
Display:
Warning: main(noFileExistsHere.php): failed to open stream: No such file or directory in /home/websiteName/FolderName/tizagScript.php on line 2 Warning: main(): Failed opening 'noFileExistsHere.php' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/websiteName/FolderName/tizagScript.php on line 2 Hello World!
Notice that our echo statement is still executed, this is because a Warning does not prevent our PHP script from running. On the other hand, if we did the same example but used the require statement we would get something like the following example.
PHP Code:

require("noFileExistsHere.php");
echo "Hello World!";
?>
Display:
Warning: main(noFileExistsHere.php): failed to open stream: No such file or directory in /home/websiteName/FolderName/tizagScript.php on line 2 Fatal error: main(): Failed opening required 'noFileExistsHere.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/websiteName/FolderName/tizagScript.php on line 2
The echo statement was not executed because our script execution died after the require function returned a fatal error! We recommend that you use require instead of include because your scripts should not be executing if necessary files are missing or misnamed.

PHP Strings and Operators with example tutorial


PHP - Strings
In the last lesson, PHP Echo, we used strings a bit, but didn't talk about them in depth. Throughout your PHP career you will be using strings a great deal, so it is important to have a basic understanding of PHP strings.
PHP - String Creation
Before you can use a string you have to create it! A string can be used directly in a function or it can be stored in a variable. Below we create the exact same string twice: first storing it into a variable and in the second case we place the string directly into a function.
PHP Code:
$my_string = "Tizag - Unlock your potential!";
echo "Tizag - Unlock your potential!";
echo $my_string;
In the above example the first string will be stored into the variable $my_string, while the second string will be used in the echo function and not be stored. Remember to save your strings into variables if you plan on using them more than once! Below is the output from our example code. They look identical just as we thought.
Display:
Tizag - Unlock your potential! Tizag - Unlock your potential!
PHP - String Creation Single Quotes
Thus far we have created strings using double-quotes, but it is just as correct to create a string using single-quotes, otherwise known as apostrophes.
PHP Code:
$my_string = 'Tizag - Unlock your potential!';
echo 'Tizag - Unlock your potential!';
echo $my_string;
If you want to use a single-quote within the string you have to escape the single-quote with a backslash \ . Like this: \' !
PHP Code:
echo 'Tizag - It\'s Neat!';
PHP - String Creation Double-Quotes
We have used double-quotes and will continue to use them as the primary method for forming strings. Double-quotes allow for many special escaped characters to be used that you cannot do with a single-quote string. Once again, a backslash is used to escape a character.
PHP Code:
$newline = "A newline is \n";
$return = "A carriage return is \r";
$tab = "A tab is \t";
$dollar = "A dollar sign is \$";
$doublequote = "A double-quote is \"";
Note: If you try to escape a character that doesn't need to be, such as an apostrophe, then the backslash will show up when you output the string.
These escaped characters are not very useful for outputting to a web page because HTML ignore extra white space. A tab, newline, and carriage return are all examples of extra (ignorable) white space. However, when writing to a file that may be read by human eyes these escaped characters are a valuable tool!
PHP - String Creation Heredoc
The two methods above are the traditional way to create strings in most programming languages. PHP introduces a more robust string creation tool called heredoc that lets the programmer create multi-line strings without using quotations. However, creating a string using heredoc is more difficult and can lead to problems if you do not properly code your string! Here's how to do it:
PHP Code:
$my_string = <<
Tizag.com
Webmaster Tutorials
Unlock your potential!
TEST;
echo $my_string;
There are a few very important things to remember when using heredoc.
• Use <<< and some identifier that you choose to begin the heredoc. In this example we chose TEST as our identifier.
• Repeat the identifier followed by a semicolon to end the heredoc string creation. In this example that was TEST;
• The closing sequence TEST; must occur on a line by itself and cannot be indented!
Another thing to note is that when you output this multi-line string to a web page, it will not span multiple lines because we did not have any
tags contained inside our string! Here is the output made from the code above.
Display:
Tizag.com Webmaster Tutorials Unlock your potential!
Once again, take great care in following the heredoc creation guidelines to avoid any headaches.
PHP - Operators
In all programming languages, operators are used to manipulate or perform operations on variables and values. You have already seen the string concatenation operator "." in the Echo Lesson and the assignment operator "=" in pretty much every PHP example so far.
There are many operators used in PHP, so we have separated them into the following categories to make it easier to learn them all.
• Assignment Operators
• Arithmetic Operators
• Comparison Operators
• String Operators
• Combination Arithmetic & Assignment Operators
Assignment Operators
Assignment operators are used to set a variable equal to a value or set a variable to another variable's value. Such an assignment of value is done with the "=", or equal character. Example:
• $my_var = 4;
• $another_var = $my_var
Now both $my_var and $another_var contain the value 4. Assignments can also be used in conjunction with arithmetic operators.
Arithmetic Operators
Operator
English
Example
+
Addition
2 + 4
-
Subtraction
6 - 2
*
Multiplication
5 * 3
/
Division
15 / 3
%
Modulus
43 % 10
PHP Code:
$addition = 2 + 4;
$subtraction = 6 - 2;
$multiplication = 5 * 3;
$division = 15 / 3;
$modulus = 5 % 2;
echo "Perform addition: 2 + 4 = ".$addition."
";
echo "Perform subtraction: 6 - 2 = ".$subtraction."
";
echo "Perform multiplication: 5 * 3 = ".$multiplication."
";
echo "Perform division: 15 / 3 = ".$division."
";
echo "Perform modulus: 5 % 2 = " . $modulus
. ". Modulus is the remainder after the division operation has been performed.
In this case it was 5 / 2, which has a remainder of 1.";
Display:
Perform addition: 2 + 4 = 6 Perform subtraction: 6 - 2 = 4 Perform multiplication: 5 * 3 = 15 Perform division: 15 / 3 = 5 Perform modulus: 5 % 2 = 1. Modulus is the remainder after the division operation has been performed. In this case it was 5 / 2, which has a remainder of 1.
Comparison Operators
Comparisons are used to check the relationship between variables and/or values. If you would like to see a simple example of a comparison operator in action, check out our If Statement Lesson. Comparison operators are used inside conditional statements and evaluate to either true or false. Here are the most important comparison operators of PHP. Assume: $x = 4 and $y = 5;
Operator
English
Example
Result
==
Equal To
$x == $y
false
!=
Not Equal To
$x != $y
true
<
Less Than
$x < $y
true
>
Greater Than
$x > $y
false
<=
Less Than or Equal To
$x <= $y
true
>=
Greater Than or Equal To
$x >= $y
false
String Operators
As we have already seen in the Echo Lesson, the period "." is used to add two strings together, or more technically, the period is the concatenation operator for strings.
PHP Code:
$a_string = "Hello";
$another_string = " Billy";
$new_string = $a_string . $another_string;
echo $new_string . "!";
Display:
Hello Billy!
Combination Arithmetic & Assignment Operators
In programming it is a very common task to have to increment a variable by some fixed amount. The most common example of this is a counter. Say you want to increment a counter by 1, you would have:
• $counter = $counter + 1;
However, there is a shorthand for doing this.
• $counter += 1;
This combination assignment/arithmetic operator would accomplish the same task. The downside to this combination operator is that it reduces code readability to those programmers who are not used to such an operator. Here are some examples of other common shorthand operators. In general, "+=" and "-=" are the most widely used combination operators.
Operator
English
Example
Equivalent Operation
+=
Plus Equals
$x += 2;
$x = $x + 2;
-=
Minus Equals
$x -= 4;
$x = $x - 4;
*=
Multiply Equals
$x *= 3;
$x = $x * 3;
/=
Divide Equals
$x /= 2;
$x = $x / 2;
%=
Modulo Equals
$x %= 5;
$x = $x % 5;
.=
Concatenate Equals
$my_str.="hello";
$my_str = $my_str . "hello";
Pre/Post-Increment & Pre/Post-Decrement
This may seem a bit absurd, but there is even a shorter shorthand for the common task of adding 1 or subtracting 1 from a variable. To add one to a variable or "increment" use the "++" operator:
• $x++; Which is equivalent to $x += 1; or $x = $x + 1;
To subtract 1 from a variable, or "decrement" use the "--" operator:
• $x--; Which is equivalent to $x -= 1; or $x = $x - 1;
In addition to this "shorterhand" technique, you can specify whether you want the increment to before the line of code is being executed or after the line has executed. Our PHP code below will display the difference.
PHP Code:
$x = 4;
echo "The value of x with post-plusplus = " . $x++;
echo "
The value of x after the post-plusplus is " . $x;
$x = 4;
echo "
The value of x with with pre-plusplus = " . ++$x;
echo "
The value of x after the pre-plusplus is " . $x;
Display:
The value of x with post-plusplus = 4 The value of x after the post-plusplus is = 5 The value of x with with pre-plusplus = 5 The value of x after the pre-plusplus is = 5
As you can see the value of $x++ is not reflected in the echoed text because the variable is not incremented until after the line of code is executed. However, with the pre-increment "++$x" the variable does reflect the addition immediately.
Using Comments in PHP
Comments in PHP are similar to comments that are used in HTML. The PHP comment syntax always begins with a special character sequence and all text that appears between the start of the comment and the end will be ignored by the browser.
In HTML a comment's main purpose is to serve as a note to you, the web developer or to others who may view your website's source code. However, PHP's comments are different in that they will not be displayed to your visitors. The only way to view PHP comments is to open the PHP file for editing. This makes PHP comments only useful to PHP programmers.
In case you forgot what an HTML comment looked like, see our example below.
HTML Code:

PHP Comment Syntax: Single Line Comment
While there is only one type of comment in HTML, PHP has two types. The first type we will discuss is the single line comment. The single line comment tells the interpreter to ignore everything that occurs on that line to the right of the comment. To do a single line comment type "//" and all text to the right will be ignored by PHP interpreter.
PHP Code:

echo "Hello World!"; // This will print out Hello World!
echo "
Psst...You can't see my PHP comments!"; // echo "nothing";
// echo "My name is Humperdinkle!";
?>
Display:
Hello World! Psst...You can't see my PHP comments!
Notice that a couple of our echo statements were not evaluated because we commented them out with the single line comment. This type of line commenting is often used for quick notes about complex and confusing code or to temporarily remove a line of PHP code.
PHP Comment Syntax: Multiple Line Comment
Similiar to the HTML comment, the multi-line PHP comment can be used to comment out large blocks of code or writing multiple line comments. The multiple line PHP comment begins with " /* " and ends with " */ ".
PHP Code:

/* This Echo statement will print out my message to the
the place in which I reside on. In other words, the World. */
echo "Hello World!";
/* echo "My name is Humperdinkle!";
echo "No way! My name is Uber PHP Programmer!";
*/
?>
Display:
Hello World!
Good Commenting Practices
One of the best commenting practices that I can recommend to new PHP programmers is....USE THEM!! So many people write complex PHP code and are either too lazy to write good comments or believe the commenting is not needed. However, do you really believe that you will remember exactly what you were thinking when looking at this code a year or more down the road?
Let the comments permeate your code and you will be a happier PHPer in the future. Use single line comments for quick notes about a tricky part in your code and use multiple line comments when you need to describe something in greater depth than a simple note.

PHP - Variables with Example tutorial


PHP - Variables
If you have never had any programming, Algebra, or scripting experience, then the concept of variables might be a new concept to you. A detailed explanation of variables is beyond the scope of this tutorial, but we've included a refresher crash course to guide you.
A variable is a means of storing a value, such as text string "Hello World!" or the integer value 4. A variable can then be reused throughout your code, instead of having to type out the actual value over and over again. In PHP you define a variable with the following form:
• $variable_name = Value;
If you forget that dollar sign at the beginning, it will not work. This is a common mistake for new PHP programmers!
A Quick Variable Example
Say that we wanted to store the values that we talked about in the above paragraph. How would we go about doing this? We would first want to make a variable name and then set that equal to the value we want. See our example below for the correct way to do this.


PHP Code:

$hello = "Hello World!";
$a_number = 4;
$anotherNumber = 8;
?>
Note for programmers: PHP does not require variables to be declared before being initialized.
PHP Variable Naming Conventions
There are a few rules that you need to follow when choosing a name for your PHP variables.
• PHP variables must start with a letter or underscore "_".
• PHP variables may only be comprised of alpha-numeric characters and underscores. a-z, A-Z, 0-9, or _ .
• Variables with more than one word should be separated with underscores. $my_variable
• Variables with more than one word can also be distinguished with capitalization. $myVariable


PHP - Echo
As you saw in the previous lesson, the PHP function echo is a means of outputting text to the web browser. Throughout your PHP career you will be using the echo function more than any other. So let's give it a solid perusal!
Outputting a String
To output a string, like we have done in previous lessons, use the PHP echo function. You can place either a string variable or you can use quotes, like we do below, to create a string that the echo function will output.


PHP Code:

$myString = "Hello!";
echo $myString;
echo "
I love using PHP!
";
?>
Display:
Hello!
I love using PHP!
In the above example we output "Hello!" without a hitch. The text we are outputting is being sent to the user in the form of a web page, so it is important that we use proper HTML syntax!
In our second echo statement we use echo to write a valid Header 5 HTML statement. To do this we simply put the
at the beginning of the string and closed it at the end of the string. Just because you're using PHP to make web pages does not mean you can forget about HTML syntax!
Careful When Echoing Quotes!
It is pretty cool that you can output HTML with PHP. However, you must be careful when using HTML code or any other string that includes quotes! The echo function uses quotes to define the beginning and end of the string, so you must use one of the following tactics if your string contains quotations:
• Don't use quotes inside your string
• Escape your quotes that are within the string with a slash. To escape a quote just place a slash directly before the quotation mark, i.e. \"
• Use single quotes (apostrophes) for quotes inside your string.
See our example below for the right and wrong use of the echo function:


PHP Code:

// This won't work because of the quotes around specialH5!
echo "
I love using PHP!
";
// OK because we escaped the quotes!
echo "
I love using PHP!
";
// OK because we used an apostrophe '
echo "
I love using PHP!
";
?>
If you want to output a string that includes quotations, either use an apostrophe ( ' ) or escape the quotations by placing a slash in front of it ( \" ). The slash will tell PHP that you want the quotation to be used within the string and NOT to be used to end echo's string.
Echoing Variables
Echoing variables is very easy. The PHP developers put in some extra work to make the common task of echoing all variables nearly foolproof! No quotations are required, even if the variable does not hold a string. Below is the correct format for echoing a variable.


PHP Code:

$my_string = "Hello Bob. My name is: ";
$my_number = 4;
$my_letter = a;
echo $my_string;
echo $my_number;
echo $my_letter;
?>
Display:
Hello Bob. My name is: 4a
Echoing Variables and Text Strings
You can also combine text strings and variables. By doing such a conjunction you save yourself from having to do a large number of echo statements. Variables and text strings are joined together with a period( . ). The example below shows how to do such a combination.


PHP Code:

$my_string = "Hello Bob. My name is: ";
$newline = "
";
echo $my_string."Bobettta".$newline;
echo "Hi, I'm Bob. Who are you? ".$my_string.$newline;
echo "Hi, I'm Bob. Who are you? ".$my_string."Bobetta";
?>
Display:
Hello Bob. My name is: Bobetta Hi, I'm Bob. Who are you? Hello Bob. My name is: Hi, I'm Bob. Who are you? Hello Bob. My name is: Bobetta
This combination can be done multiple times, as the example shows. This method of joining two or more strings together is called concatenation and we will talk more about this and other forms of string manipulation in our string lesson.

Php Syntax with Example Tutorial


PHP - Syntax
Before we talk about PHP's syntax, let us first define what syntax is referring to.
• Syntax - The rules that must be followed to write properly structured code.
PHP's syntax and semantics are similar to most other programming languages (C, Java, Perl) with the addition that all PHP code is contained with a tag, of sorts. All PHP code must be contained within the following...


PHP Code:

?>
or the shorthand PHP tag that requires shorthand support to be enabled
on your server...

?>
If you are writing PHP scripts and plan on distributing them, we suggest that you use the standard form (which includes the ?php) rather than the shorthand form. This will ensure that your scripts will work, even when running on other servers with different settings.

How to Save Your PHP Pages
If you have PHP inserted into your HTML and want the web browser to interpret it correctly, then you must save the file with a .php extension, instead of the standard .html extension. So be sure to check that you are saving your files correctly. Instead of index.html, it should be index.php if there is PHP code in the file.
Example Simple HTML & PHP Page
Below is an example of one of the easiest PHP and HTML page that you can create and still follow web standards.

PHP and HTML Code:


My First PHP Page



echo "Hello World!";
?>


Display:
Hello World!

If you save this file and place it on PHP enabled server and load it up in your web browser, then you should see "Hello World!" displayed. If not, please check that you followed our example correctly.
We used the PHP function echo to write "Hello World!" and we will be talking in greater depth about this PHP function and many others later on in this tutorial.
The Semicolon!
As you may or may not have noticed in the above example, there was a semicolon after the line of PHP code. The semicolon signifies the end of a PHP statement and should never be forgotten. For example, if we repeated our "Hello World!" code several times, then we would need to place a semicolon at the end of each statement.


PHP and HTML Code:


My First PHP Page



echo "Hello World! ";
echo "Hello World! ";
echo "Hello World! ";
echo "Hello World! ";
echo "Hello World! ";
?>


Display:
Hello World! Hello World! Hello World! Hello World! Hello World!
White Space
As with HTML, whitespace is ignored between PHP statements. This means it is OK to have one line of PHP code, then 20 lines of blank space before the next line of PHP code. You can also press tab to indent your code and the PHP interpreter will ignore those spaces as well.


PHP and HTML Code:


My First PHP Page



echo "Hello World!";
echo "Hello World!";
?>


Display:
Hello World!Hello World!
This is perfectly legal PHP code.

PHP Installation



Windows Installation

1. Download the software at: www.apachefriends.org/en/xampp-windows.html#641
Select the Installer option under the “Basic Package.” At the time of this writing, a direct link to
version 1.5 for Windows was: http://prdownloads.sourceforge.net/xampp/xampp-win32-1.5.0-pl1-
installer.exe
You may be taken to a page that gives you a bunch of different places to download from. Just click
one of the download buttons. Once downloaded, the installer works like most Windows installers.
2. Double click the .exe file you downloaded.

A window opens asking you to select the language you’d like to use.
3. Choose a language from the menu and click the OK button
A Setup Wizard window appears, ready to step you through the set up process.
4. Click the Next button, then click the Install button.
The various files needed are loaded onto your computer.
5. Click the finish button, then when a window appears saying “Install XAMPP servers as service”
appears make a selection.
A service starts up ever time you turn on your computer. In other words, do you want the Web server
and database server to startup whenever you turn on your PC? If you plan on doing a lot of
development, day-in and day-out, you might want to choose “Yes.” Otherwise you’ll find that you’re
starting up the XAMPP control panel (see below) and turning on the servers every time you boot up.
However, if you won’t be building database sites frequently, or you don’t have a lot of RAM in your
computer, you might want to choose “No.” This way you can manually turn on the servers (see “The
XAMPP Control Panel” below) when you need to work on a dynamic site.
If you select “Yes” you will be taken through the same question for the Apache Web Server, the
MySQL database server and the FileZilla FTP server. It’s best to click “No” for the FileZilla FTP
server. You won’t need it for this tutorial, and since this is just a testing server, you won’t need to have
the ability to FTP to the computer—after all, all your files are already on your computer.
6. Finally, launch a Web browser and type http://localhost/ in the location bar.
You’ll encounter a page that lists a bunch of languages; click the language you prefer and you’ll be
taken to a kind of control panel for XAMPP on your computer (see Figure PHP Tutorial 1-1.)



                     PHP Tutorial 1-1. Once installed, you can view your XAMPP page from
                                                http://localhost/xampp/


Once you’ve installed XAMPP, there will be a shortcut called XAMPP Control Panel on your desktop.
Double-click this to control the servers—you can turn the servers off and on, as well as turn them into
services which launch each time you start up your computer.
To uninstall XAMPP, just go to C:\Program Files\ and delete the folder named XAMPP. That’s it!


For more information on XAMPP, included detailed installation and setup instructions visit
www.apachefriends.org/en/xampp-windows.html.


I’m Comfortable Downloading and Installing Complex Software



Windows
• Apache Web Server: Visit the Apache Web site and download and install version 2 of the Apache
Web server: http://httpd.apache.org/download.cgi
• PHP: Go to the PHP site and download the PHP 5.05 Zip Package listed under “Windows Binaries”
at: www.php.net/downloads.php
• MySQL: Visit the MySQL download page at http://dev.mysql.com/downloads/mysql/4.0.html and
click the Windows (x86) link to download the installer.
• PHPMyAdmin: For managing your MySQL database, you’ll use this free, Web-based tool. Download
the latest version at www.phpmyadmin.net/home_page/downloads.php. You can download a ZIP file
containing all of the files. These are just PHP pages and they’ll go inside your Web documents folder.
It’s usually a good idea to create a folder in the Web site root folder with a name like pma (for
phpMyAdmin) and put all of the PHPMyAdmin files in there.



Dude, I Already Have PHP and MySQL Up and Running
OK. You’re all set, but you should make sure you either have PHPMyAdmin installed
(www.phpmyadmin.net/home_page/downloads.php) or you know how to load an SQL file into MySQL
from the command line. You’ll be doing that in the next phase of this setup.
Setting Up the Database and Web Site
To learn Dreamweaver’s dynamic features, you’ll be building a small Web application for the National
Exasperator. In fact, you’ll turn the site’s online store into dynamic Web pages that will retrieve
information from a database and merge it with already-created HTML code.
You’ll need the tutorial files to follow along. You can download them at www.sawmac.com/dw8/php.
Once you’ve downloaded and unzipped the files you’ll have a folder named DW_php, containing a folder
called nationalEx (the root folder for this Web site) and a file called nationalEx.sql (a SQL file that will let
you add the product data to your MySQL database).



Putting the Web Pages in Place
To begin, move the nationalEx folder into the Web server’s root folder. If you followed the directions
above and installed the XAMPP versions of Apache, PHP and MySQL, the root folder should be located at
C:\XAMPP\htdocs on Windows, and Applications/XAMPP/htdocs on Mac. (If your Windows computer’s
main drive is not the C:\ drive, the root folder might be located on another drive—D:\, for instance.) Place
nationalEx inside the htdocs folder.







Loading the Database
The data for the National Exasperator store needs to be installed in your new MySQL server. There’s
actually a few steps you’ll need to complete. First you’ll create a new database (you’ll be loading the data
for the store into this); next, you’ll load the data into this new database; finally, you’ll create a new user for
the database (this will be a special account that you’ll use for accessing and updating the database.)

Create the Database
1. In a Web browser type http://localhost/
If you used the XAMPP program as described above, this will take you to the main XAMPP page on
the new server. You’ll use a program called phpMyAdmin to administer the MySQL server.

2. Click the phpMyAdmin link listed under “Tools” to go to the phpMyAdmin main page.
Note: If you set up the Web server, PHP and MySQL on your own, you’ll need to use
your Web browser to go to the PHPMyAdmin folder on your server. This might be
http://localhost/pma or http://localhost/phpmyadmin/ depending on your set up.

3. In the Create New Database box type nationalEx and press the Create button (see Figure PHP Tutorial
1-3.)
This creates a new database on the MySQL server. Next you’ll load a SQL file which will create the
required tables and add the needed data to the database (see Chapter 20 for more on SQL, databases
and tables.)




                               The phpMyAdmin main page. Here you can create a new database, select an already created database to work with and handle many administrative tasks for MySQL.



4. Click the SQL tab near the top of the page.
This takes you to a page that lets you type in a SQL query (see page xx of printed book), or load a text
file that has SQL commands in it. You’ll do the latter—load a text file that contains all of the SQL
necessary to create the tables and data for the database.

5. Click the Browse button (see Figure PHP Tutorial 1-4. In the File Upload window that appears,
navigate to and select the file nationalEx.sql in the DW_PHP folder you downloaded earlier.

              phpMyAdmin lets you load a SQL file, and execute the SQLcode inside the file. This is a great way    to replicate data from another database. In fact phpMyAdmin can help you export all of the tables and data from any database it has access to.

6. Click the Go button.

The SQL in the file is executed: four new tables are created and a bunch of data is added. The last step
in prepping the database is to create a new MySQL user that has access to add to and update the
National Exasperator database.

7. Click the link at the top of the page labeled Server: Localhost.
This returns you to the main phpMyAdmin page

8. Click the Privileges link in the middle column of links.

9. Click the “Add a new user” link.




                   Create a new user to access a database.
10. Type nationalEx for the username and localhost for the Host. In the password field type nationalEx,
and in the re-type box type nationalEx again. The screen should look like Figure PHP Tutorial 1-6.
This will create a user whose name is nationalEx, whose password is nationalEx, and who can only
access them database locally from the server. This means someone out on the internet can’t try to login
to the MySQL server using the nationalEx account; only local access—for example, PHP pages being
run on the same computer—is allowed.
In general, it is a very bad idea to make a password the same as a username, since it doesn’t take much
imagination for a hacker to figure this out and suddenly be in control of your database. But for this
example application, it’s best to keep things as simple as possible, so we can get to the more interesting
stuff (actually using Dreamweaver, for instance!)
11. Click the Go button at the bottom of the page.
The new user, nationalEx, is created and you’re taken to another Web page. Now you need to give that
user access to the National Exasperator database.
12. Scroll down the page to the “Database-specific privileges” section; select nationalEx from the database
menu



Setting Up Dreamweaver
The first step in working on this dynamic Web application is to define a new site. The process of defining a
dynamic site, as outlined below, is slightly different than for static sites, but not any harder:
1. Choose Site→New Sites.
The Site Definition window opens. Use Dreamweaver’s Site Wizard to help you set up this new site.
2. If it isn’t already selected, click the Basic tab at the top of the window.
The first step is to give this new site a name.
3. Type Exasperator Store in the first box and http://www.nationalExasperator.com/ in the second box.
You’ve just told Dreamweaver the name you want to use while working on this site, and the URL of
the Web site. In a real world scenario, you’d type the address of your Web site.
4. Click Next.
The next screen lets you choose whether you’re building a static or dynamic Web site.
5. Select “Yes, I want to use a server technology” and choose PHP/MySQL from the pop-up menu. Click
Next to proceed.
In the next step, you’ll tell Dreamweaver where your local files are and where you intend to put the
files for the testing server.
6. Select “Edit and test locally”.

Dreamweaver provides three ways to work with dynamic Web page files and a testing server.
“Edit and test locally” is a good choice when you’ve set up a Web and application server on your
computer (as you’ve done in this tutorial). Essentially, this means that you’re working on a Web site
located on a functioning Web server. In this way, you’ll preview the pages running on a real Web
server, so you can immediately test out all the nifty dynamic stuff.
The other two options are used when the testing server is located on another computer. This may be a
computer on your local network, or a full-fledged Web server running on the Internet that you connect
to using FTP.
“Edit locally, then upload to remote testing server” is a good option when you can’t run a testing server
on your computer—for example you don’t have administrative privileges so you can’t install a Web
server, but you do have a Web hosting account that provides PHP and MySQL.
The last option should be used when the testing server is on another computer, but you’re the only
developer working on the files. Since the files are available on your local network, anyone in your
company or office who has access to the computer with the testing server can also edit those files.
Your Web pages can end up in an unrecoverable mess if you and someone else are simultaneously
editing and saving the exact same file.
The next step involves telling Dreamweaver where to find the files for the Web site.
7. Click the folder at the right side of the middle of the window; navigate to and select the nationalEx
folder on the Web server. Click Next.
If you used the XAMPP installation recommended in the set up instructions this will be C:\Program
Files\xampp\htdocs\nationalEx\ (on Windows) or Applications:XAMPP:htdocs:nationalEx (on Mac).
You’ve nearly completed the setup.
8. Type the URL of the test server in the box and click Test.
Dreamweaver may have already filled in this box. If the test server is running on your computer, the
URL begins with http://localhost/ and ends with the folder that contains the Web pages. In this case,
the URL is probably http://localhost/nationalEx/.
If you get an error message when you click Test, you’ve probably entered the wrong URL.
9. Click Next.
You may get a warning box squawking about how the URL doesn’t match the testing server. This just
means that in step 3 above you didn’t specify any folder, but in step 7 you said the site was in a folder
named nationalEx. This means site-root relative links (see Chapter 5) won’t work. In a real world case,
you’d probably have your site’s files in the real root folder of your local Web server so you wouldn’t
run into this error. But since this is a made up example, and you’re using document-relative links (see
chapter 5), you’re safe. So click OK to close the warning box.
10. Click No, and then click Next one more time.
If you were planning to move this site onto a Web server connected to the Internet, you would select
Yes at this stage and provide all of the information needed to move your site files to the Internet as
described in Chapter 16. But since this tutorial is just an exercise, you won’t be putting it up on a live
Web server.
11. Click Done.
Dreamweaver has successfully set up your site. You’re now ready to learn about databases and connect
Dreamweaver to the National Exasperator online store database. (You may encounter the same
warning from step 9; just click OK to dismiss it.)


Connecting Dreamweaver to a Database
1. From the Files Panel (Window→Files) double-click the file index.php.
The main page for the online store opens. You have to have a dynamic PHP page open, in order to
connect Dreamweaver to a MySQL database.
2. Open the Databases panel by choosing Window→Databases.
The Application panel group opens.
3. Click the plus sign (+) button at the top right of the panel. From the pop-up menu, choose MySQL
connection.


4. In the Connection Name box, type connNationalEx.
You can use any name you want as long as it doesn’t start with a number and doesn’t contain any
characters other than letters, numbers, and the underscore character. In this case, conn is a helpful
indicator that this is a database connection and makes identifying it easier if you ever need to look into
the underlying code of the page.
Next, you’ll tell Dreamweaver where the database is located.
5. In the MySQL server box, type localhost.
In this case, both the Web server and MySQL are set up on the same computer, so when the Web
server runs the dynamic Web pages which attempt to access the database it only needs to look at the
“localhost” where the MySQL Database Server is located.
In many cases, the MySQL server provided by your Web hosting company will also be located on the
same server, so localhost will work when you move your pages onto your Web server. This is helpful,
because it means you can develop your sites locally on your computer, move them onto the Internet
and they should be able to connect to the database without a problem.
However, some Web hosts put their databases on separate machines dedicated just for that one task. In
this case, you would need to edit the database connection, and replace localhost, which works for
development and testing on your own computer, with the address of the MySQL server—this might besomething like mysql.webhost.com (don’t use http://, or anything besides the server’s address.) Your
Web hosting company can supply this information. Unfortunately this means that you need to change
the connection file Dreamweaver creates (this is what you’re doing right now) to include the new
address. Before uploading your site, open the connection file. Do this either from the databases panel
as described on page xx of this book or by looking in a folder name Connections located in the local
root folder of your site. In that folder you’ll find a file named after the connection name you supplied
when you created the connection—in this tutorial, that’s step 4 above so in this case the name of the
connection file is connNationalEx.php. Double-click this file, change localhost to the address of your
Web host’s MySQL database server. Then upload this file to your site (see page xx for information on
uploading Web files). You can then open the connection file again and change the database address
back to localhost. This will let you continue to work and test on your local computer—just make sure
you don’t upload this file to the Web server, or you’ll wipe out the connection file that you customized
for your Web server, and your dynamic pages won’t be able to connect to the database.
6. Type nationalEx in the username box, and nationalEx in the password box.
This is the MySQL username and password you created earlier when you set up the database.
7. Click the Select button.
The Select Database window appears. This lets you pick which database you wish to connect to. In this
case it’s the National Exasperator’s online store database.
If you get an error instead, check that you spelled localhost correctly, and that you supplied the right
username and password.
8. Select nationalEx and click OK.
9. The dialog closes and nationalEx appears in the Database box at the bottom of the window. Click the
Test button.
A window saying “Connection was made successfully” should appear.
10. Click OK to close the window that appeared when you tested the connection; click OK once more to
close the MySQL connection box.
Behind the scenes, Dreamweaver creates a small PHP file and stores it in a folder called Connections
in your site’s root folder. Whenever you create a dynamic page that communicates with the database,
Dreamweaver adds a line of code pointing to this connection file. (The file’s name reflects the
connection name you typed in step 4—here it’s connNationalEx.php.)







PHP Tutorial From beginner



PHP is a powerful tool for making dynamic and interactive Web pages.
PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.
In our PHP tutorial you will learn about PHP, and how to execute scripts on your server
Pre-requisites
Before you continue you should have a basic understanding of the following:
• HTML/XHTML
• JavaScript
What is PHP?
• PHP stands for PHP: Hypertext Preprocessor
• PHP is a server-side scripting language, like ASP
• PHP scripts are executed on the server
• PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)
• PHP is an open source software
• PHP is free to download and use
What is a PHP File?
• PHP files can contain text, HTML tags and scripts
• PHP files are returned to the browser as plain HTML
• PHP files have a file extension of ".php", ".php3", or ".phtml"
What is MySQL?
• MySQL is a database server
• MySQL is ideal for both small and large applications
• MySQL supports standard SQL
• MySQL compiles on a number of platforms
• MySQL is free to download and use
PHP + MySQL
• PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix platform)
Why PHP?
• PHP runs on different platforms (Windows, Linux, Unix, etc.)
• PHP is compatible with almost all servers used today (Apache, IIS, etc.)
• PHP is FREE to download from the official PHP resource: www.php.net
• PHP is easy to learn and runs efficiently on the server side
Where to Start?
To get access to a web server with PHP support, you can:
• Install Apache (or IIS) on your own server, install PHP, and MySQL
• Or find a web hosting plan with PHP and MySQL support
PHP Installation
What do you need?
Most people would prefer to install a all-in-one solution:
WampServer 2.0i [07/11/09]  for Windows platform Includes : - Apache 2.2.11 - MySQL 5.1.36 - PHP 5.3.0
http://www.wampserver.com/en/
http://lamphowto.com/  for Linux platform
Already have a web server?
If your server supports PHP you don't need to do anything.
Just create some .php files in your web directory, and the server will parse them for you. Because it is free, most web hosts offer PHP support. However, if your server does not
support PHP, you must install PHP. Here is a link to a good tutorial from PHP.net on how to install PHP5:
http://www.php.net/manual/en/install.php
Download PHP
Download PHP for free here: http://www.php.net/downloads.php
Download MySQL Database
Download MySQL for free here: http://www.mysql.com/downloads/index.html
Download Apache Server
Download Apache for free here: http://httpd.apache.org/download.cgi
Download a nice text editor [Not required]
http://www.flos-freeware.ch/notepad2.html
PHP Syntax
PHP code is executed on the server, and the plain HTML result is sent to the browser.
Basic PHP Syntax
A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block can be placed anywhere in the document.
On servers with shorthand support enabled you can start a scripting block with <? and end with ?>.
For maximum compatibility, we recommend that you use the standard form (<?php) rather than the shorthand form.
<?php ?>
A PHP file normally contains HTML tags, just like an HTML file, and some PHP scripting code.
Below, we have an example of a simple PHP script which sends the text "Hello World" to the browser:
<html> <body> <?php echo "Hello World"; ?> </body> </html>
Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish one set of instructions from another.
There are two basic statements to output text with PHP: echo and print. In the example above we have used the echo statement to output the text "Hello World".
Note: The file must have a .php extension. If the file has a .html extension, the PHP code will not be executed.
Comments in PHP
In PHP, we use // to make a single-line comment or /* and */ to make a large comment block.
<html> <body> <?php //This is a comment /* This is a comment block */ ?> </body> </html>