Learn PHP by Examples

May 15th, 2008 | By sguler | Category: Featured, Php

Since you are here to learn Php by examples, I’m assuming you have intermediate knowledge of HTML at least. So I will give you examples of easy php scripts that will teach you how php works. First of all, what is PHP ?

What is PHP ?

PHP is a server-side HTML-embedded scripting language, as PHP.net (PHP Homepage) stated. Meaning, PHP is generally embedded into HTML. When someone visits your PHP page, server compiles it and translates to plain HTML, before sending to visitor. Visitor only gets the HTML coded page which is formed by PHP script. That’s why they call PHP as a Server-Side Scripting Language.

Php Server Side Scripting

Now, you know that you won’t be able to view your php files using your internet browsers without putting them on a server. You need a server to put your php files. You have two choices, you can form your PC into a server, meaning you can install apache web server software (working as a php-compiler) on your PC or you can buy a php included web hosting server.

* Installing Apache (PHP,MySql) Server on your PC ?
Easy. Just install Xampp (XAMPP is an easy to install Apache distribution containing MySQL, PHP and Perl) on your PC, and your PC will be your own web server. Xampp Installation Link

* Web Hosting ?
I suggest you try free web hosting services. Choose your free php hosting service from this page. Sign-up for free using a subdomain.

Now, we can start if you have a server to test your php files. But before starting, I suggest you install Adobe’s Dreamweaver which has an easy php-html editor. It is useful for everyone, it will help you much.

Here is the contents of this Php Tuturial:

Contents:

PHP Examples

Let’s start learning. Open your text-editor or if you have dreamweaver installed, open a new file selecting Php. Don’t forget to save your file with the extension “.php” before putting into server.

<?php
?>

This is a very basic php code. Php scripts, start with “<?php” tag and end with “?>” tag. While your server is reading that line starting with “<?php”, it will know that a php script is starting, and it will compile and translate it to html.

In the above example, you see a commented line. Two slashes defines the following line as a comment. Server will ignore the line and will continue with the next line.

HTML & PHP – Hello World Example

Below code demostrates the use of PHP with HTML. This code will print “Hello World” on the line php tag is, which will be inside the Html codes.

Save this code as “test.php”, put it into your server and access it using your internet browser. Server will compile and send you below html code.

Hello World!

In that php script, we have printed inside of the quotation marks with php’s function “echo”. Echo is a function that outputs/prints the string defined in quotation marks. You also should know that string in PHP is defined inside quotation marks. In addition to this, pay attention to the semicolon at the end of the echo function. Every statement in php must be ended with semicolons.

A little more in the below example:

Hello World!";
?&gt;

When the server compiles the above code, it will generate the code below. The reason of using backslash before the quotation mark is to escape from quotation mark. Because first quotation mark starts the string and the second ends the string. If we do not escape from that quotation, the php script leads to an error since there is no function called “color” in php which is come after quotation. So we have to define all of the line with span tag and its inside as one string. This is done adding quotation marks at the beginning and also ending of the string. If the string, as in the above example, contains quotation marks, we do escape from that character using backslash (”\”).

<span style="color: red;">Hello World!</span>
Variables in PHP

Variables in php is defined by the beginning character of “$” and followed by the name of variable. Here is an example.

In the above code, there are three variables defined: site, days_in_week and weeks. Those are defined but will not printed unless you call and output them somewhere in your script. Here is an example demonstrating how we use them.

Two things are new to you at the above code. First, we defined a new variable multiplying two other variables. Multiplying numbers is done with “*” (Multiply) sign in php. The second one is inside of the echo function. We have combined three strings and printed. As you see, combining/joining two or mor variables is done by adding dots (.) besides of the variables. We may define a new variable by doing this. See this:

Heredoc String Creation

There is an alternative way of defining strings in php. It is done by heredoc tool. Heredoc’s syntax is <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation. Here is an example:

This code will be translated to the below code by the php server.

Example of string
spanning multiple lines
using heredoc syntax.
PHP Operators

* Assignment Operators:
Equal character, “=”, is used to assign variables,values or strings to variables.
- $my_var=$your_var;

* Arithmetic Operators

  • Addition +
  • Subtraction -
  • Multiplication *
  • Division /
  • Modulus %

Here is an example:

diff is $diff
mul is $mul
div is $div
mod is $mod
TEST;
?&gt;

The server will output the below code.

total is 6
diff is 4
mul is 24
div is 6
mod is 1

*Comparison Operators

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
Comparison operators are used for checking relationships of two variables or values. The result will be in true/false type. We’ll see the use of comparison operators later.

*Other 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”;
++ Increment $x++; $x = $x + $x;
++ Decrement $x–; $x = $x – $x;
Include Function

PHP’s include is one of the most widely used functions. It simply, inserts the file defined into the php script. Meaning, you can use variables, functions and classes of the inserted file in your php script. Here is a simple example that will explain you more.

vars.php:

index.php:

Output of index.php would be following html code.

Guest, Welcome to WoWebmaster.com

As you see, we used the variable defined in vars.php by including it in index.php.

IF Statements
if (condition1) {
statement1;
} elseif (condition2) {
statement2;
else {
statement3;
}
nextline;

If statements, also, are one of the most widely used constructs of programming languages. If construct, is the important part of decision making algorithms. It allows conditional code execution. It checks whether a condition is true and the statement inside the construct is executed depending on the condition.

In the illustration above, if construct checks whether condition1 is true, if so, statement1 is executed, then statement2 and statement3 is ignored and the program jumps out of if construct, executing next line.

If condition1 is false, then condition2 is checked, if it is true, only statement2 is executed before jumping to nextline statement. If condition2 is also false, only statement3 is executed.

An Example:

Now we will explain the example line by line. We defined a $who variable on the first line. It is a string containing “user”. In the second line, an if construct is defined. First condition to check is inside the first parenthesis which has $who == “guest” condition. If the variable, $who, equals to “quest”, then the statement defined inside the brackets is executed and without checking other conditions, program jumps out of if statements. In the example, $who does not equal to “guest”, instead, it equals to “user”. As a result, only elseif construct’s condition is executed, which outputs a “Welcome” on the screen.

Another Example:
values.php:

index.php:

In the example above, first, the program will check whether $var is 0, which is false, then the program will check the second condition which is also false. Since both conditions are not met, the program will only execute the last statement which is inside of else statement’s brackets. Following code is the output of the above code.

No, the value is 3
Switch Statements

Switch is an alternative way of condition checking. With Switch statements, you can compare a same variable (or expression) against different cases quickly instead of using lots of elseif statements. Again, we will illustrate the use of it with an example:

Switch statements compares a variable against cases defined, if one case is exactly the same with the variable, then only the statement under that case is executed. If no case equals to the variable then the statement under default line is executed. If you don’t write a break statement at the end of a case’s statement list, PHP will go on executing the statements of the following case.

User Defined Functions

Function is the name that is given to a special block of statements, when called, the block of statements are executed. Every function has a name, which you can call that special function anywhere in your script after defined.
Defining a function:

function_name (){
}
?&gt;

Functions are usually used with parameters. Parameters appear in parantheses which is come after the function name and they can be used in the statements that function includes. Here is a usage example:
index.php:

output:
:) world of webmaster

As seen above, the variable $var is defined as a parameter of printing function. This is done in the last line of the php script, printing function is called with the parameter $var. When called, the printing function accesses the value of $var using $text variable.

Some examples with the outputs below:
functions.php:

index.php

the output:
In Total: $60.50

In the example above, we created a file, “functions.php”, that contain calc function. Our aim is to calculate the total price of a purchase. To simplify things, the purchase only comprises of tshirts. Our function calc has two parameters. First is tshirt’s price ($tshirt) and the second parameter is number of tshirts purchased ($number). Our calc function simply multiplies numbers by tshirt price and then adds the 10% tax.

Functions Returning Values
Functions can also return values to the user. This is accomplished by adding “return variable;” at the end of the function. It’s easy, here is an example:

output:

Php Tutorials by Wowebmaster.com

As seen above, makebold() function returned a value, which is a string, and we used that returning value by outputting (echo). Meaning, in the last line of code, makebold has a string value, that can be used like a variable.

One more example:

Arrays

An array is a data structure that stores different values in one variable. Each array in php, has a key and a corresponding value.

$array_name[key]=value

Key and Values of the array can be a string or number.

A numerically indexed array
$names[0]=”john”;
$names[1]=”elizabeth”;
$names[2]=”ahmed”;
$names[3]=”michael”;
$names[4]=”carmen”;

$names variable is an array, and has a length of 5. This is quiet useful for storing data by grouping.

Associative Arrays
$ages["john"]=23;
$ages["elizabeth"]=24;
$ages["ahmed"]=21;
$ages["michael"]=23;
$ages["carmen"]=23;

$ages variable is an array also, its keys are values (strings). Every key has associated with an age in this array. We will see usage examples after learning loops in php.

While Loops

While loops in php are continuous executing code blocks until a condition returns false.

while( condition ){
expression;
}
somecode;

Here how loop works:

  • 1: Condition inside while statement is checked
  • 2: If the condition is true, expression is executed, if false jump out of while loop and execute somecode.
  • 3: Jump back to state 1, check the condition again.

Above example, outputs numbers 1 to 10. Remember $i++ means $i=$i+1. While $i is smaller than 10, $i is printed and then incremented. After incrementing, $i<=10 condition is checked and the loop goes on until $i reaches 11.

output:

john
carmen
elizabeth
robert
michael

Above example, prints an array’s elements with while loop. We now explain the script line by line.

  • On the first line, we started to fill an array by defining its first element, $values[0]=”john”. The numeric id starts with a zero “0″.
  • On the second, third, fourth and fifth lines, elements of the array are assigned in order. Those 5 lines also can achieved by array function, which is $values=array(”john”,”carmen”,”elizabeth”,”robert”,”michael”);.
  • Our loop’s counter, also used as key of our array, is assigned a starting value, which maps to the first element of the array.
  • On the seventh line, while loop starts with condition ($i<5). If condition is not met, the program jumps to the 10th line (out of while loop).
  • Array’s current element is output on the 8nd line. $i is used as key of our array $values.
  • $i is incremented to point to the next element of the array.
  • Program returns to the seventh line again.

From the above explanation, you should understand that the loop is repeated 5 times, outputting the corresponding element of the array within each loop.

For Loops

For loops in php is similar to while loops. The difference is that you set up your own loop counter with your condition beside.

This code, actually, does the same thing that the example of while loop does. In for loops, your counter’s initial value must be set inside of the parentheses and after placing your condition, you must also add a counter behavior, it can be $i++; $i– or something similar. At first execution of for loop, the initial value is set, and then in every loop, the condition is checked and counter’s behavior is executed.

HTML Forms & Usage

Forms in web sites, are used to gather information from the visitors of website. In the example below, we will demonstrate a very easy html form, that gets the required information for a user to subscribe a website’s sources.

<form action="process.php" enctype="multipart/form-data" method="post">
<label>Your Name:
<input name="name" type="text" /></label>
<label>Your E-mail:
<input name="email" type="text" /></label>
<label>Subscription Type:
<select name="type"><option>Weekly</option><option>Monthly</option></select>
 
</label>
<input name="submit" type="submit" value="Submit" />
</form>

Output:

The form, asks for user to type his/her name, e-mail and subscription type. When the user hits the submit button, the form sends all the information using multipart/form-data encryption, to process.php with POST method.

How to get the values sent by form?
With the POST method, sent values can be accessed using the associative array, $_POST. Allt the information, is assigned to $_POST, names of the form tags as keys, and the value of the form tags as values of the array. Here is how it is done.

If the user types his name as “John Mayer”, his e-mail as “[email protected]” and his subscription type as “Weekly”. The output would be the following:


Hello John Mayer
You have subscribed with the e-mail address: [email protected]
Subscription type: Weekly

As seen above codes, our html form has 3 inputs, with names: name, e-mail and type. All of the values sent by form, is stored into the associative array, $_POST, as it did in our form: $_POST['name'], $_POST['e-mail'] and $_POST['type'].

GET Method
Another form of passing variables with a form, is GET method. Using this method, the html form, passes form variables by appending them into the url. Think we have three form inputs: name, sirname and email. When user submits the form, the url to go would be the following.

process.php?name=john&sirname=mayer&[email protected]

All the variables in the url, is splitted with a “&” sign and the question mark after file name, is to tell the web browser that the following items are variables. Here is an example form using get method.

index.html:

<form action="process.php" enctype="multipart/form-data" method="get">
<label>Purchase:
<select name="shop"><option>Tshirts</option><option>Books</option></select>
 
</label>
<label>Quantity:
<input name="quantity" size="2" type="text" /> </label>
<input name="submit" type="submit" value="Submit" />
</form>

output:

url:
process.php?shop=Tshirts&quantity=2

process.php:

output:
You purchased 2 Tshirts.

In the above example, user, first, is asked to type what and how many he will buy. When he hits the submit button, the web browser will go to process.php?shop=Tshirts&quantity=2 querying process.php. Process.php will process the posted values, and output to the screen as seen above.

Now we go a little bit more. We will have one file, that has the form and also the form processor in. First we will examine if the user submitted the form, if so, the form processor script will be executed, if user did not submit any form, the file will again output the form to user’s screen. Here is the code:

index.php:

<label>Purchase:
<select name="shop"><option>Tshirts</option><option>Books</option></select>
 
</label>
<label>Quantity:
<input name="quantity" size="2" type="text" /> </label>
<input name="Submit" type="submit" value="Submit" />
 
FORM;
echo $form;
} else {
echo "You have purchased ".$_POST['quantity']." ".$_POST['shop']." .";
echo "Thanks for choosing us! ";
 
}
?&gt;

Form Submitted, Output:
You have purchased 2 Books .Thanks for choosing us!

Form Not Submitted, Output:

The above code, first checks if user submitted the form, if not, the script outputs $form which has the form in, else, the script accesses “posted” variables using $_POST and executes the required processes.

Mysql & Usage in PHP

We’ve seen to gather information using html forms. However the important thing is to store this information in a database, to reach whenever needed. Mysql is the most widely used database to store information in PHP. So now, we’re going to demonstrate the usage of mysql and php together.

Connecting to a MySQL database
It can be done with two functions, mysql_connect and mysql_pconnect (persistent connection).

In the above code, mysql connection is created using mysql_connect function, “localhost” is the name of server (it can be an IP either), “mysql_user” and “mysql_password” are username and password of mysql installation on the server.

MySQL Tables
MySQL tables, are like associative arrays in someway, every row of the table has an index that corresponds to a value. That is to store values and sort them.

Id E-mail Subscription Type
1 [email protected] Weekly
2 [email protected] Monthly
3 [email protected] Monthly
4 [email protected] Weekly
5 [email protected] Monthly

Above table, can be shown as a sample mysql table. In mysql, when 4th row is selected on this table, all the column values can be associated with an array, which you can use later.

So how do we create tables using php? Not hard, here is an example:

';
mysql_select_db("database_name");  // selecting a database
mysql_query("CREATE TABLE subscribers(id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), email VARCHAR(30), type VARCHAR(30))");
mysql_close($link);
?&gt;

Line by line, explanation of the above code:

  • First, we create a mysql connection, localhost is the host name, mysql_user and mysql_password are login information of mysql database. Mysql connection’s status is assigned to $link variable. Mysql_connect function returns a MySQL link identifier on success, or FALSE on failure.
  • With the IF conditional statement block, mysql connection is checked. If there is no connection ($link=false); the php script will end the program with die function.
  • If there is a connection to mysql database, the program will go on executing echo function, which will output “Connected Successfully”.
  • mysql_query() sends a unique query to the currently active database ($link) on the server. The query on the above code creates a table with columns: id, e-mail and type. Id is defined to have integer numbers (int), email and type columns can have varchar type.
  • On the last line, mysql connection is closed with mysql_close function.

Mysql Training: Widely Used Queries

$query ="CREATE TABLE subscribers (id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), e-mail VARCHAR(30), type VARCHAR(30))"; /* Subscribers table created, columns: id, e-mail,type */
 
$query ="DELETE FROM subscribers WHERE e-mail='[email protected]' LIMIT 1"; /*[email protected]'s all information is removed from the database */
 
$query ="INSERT INTO subscribers (id, e-mail, type) VALUES ('', '[email protected]', 'weekly');"; /*Inserting new subscriber on subscribers database. id is auto incremented based on the previous row, e-mail and type will have values, [email protected] and weekly*/
 
$query ="UPDATE subscribers SET e-mail='[email protected]', type='monthly' WHERE id='113' LIMIT 1;";  /*Updating a row*/
 
$query="SELECT * FROM subscribers";  // All subscribers selected
 
$query ="SELECT * FROM subscribers WHERE type='Weekly'";  /* Weekly subscribers selected*/
 
$query ="SELECT id,email FROM subscribers WHERE type='Monthly'";  /* Monthly subscribers' id and email columns are selected */
 
$query ="SELECT * FROM subscribers WHERE type='Monthly' LIMIT 0, 5";  /*5 Montly subscribers selected */

Ok, now you’ve seen some widely used queries above, we can go further with a complex example.

Example: Subscriber Form & List

If you haven’t understood the code on the above examples, you may get a better idea of how mysql works, in this example. We will have three files, one for creating a table, one for your users to subscribe your website and one for you to list all the subscribers.

Create_Table.php
The first step to form a subscriber system, is to have a mysql table for it. Let’s store our subscribers’ name, e-mail and subscription type. To sort our list, we should also need an ID for every user. Hence, we create a table with id, name, e-mail and type columns. Here is the php script to create this table.

Subscribe.php
In this file, we have an if conditional statement which will be checking if the form submitted, if submitted, all the data is stored on the mysql, if not submitted, the subscription form will be printed on the screen.

<label for="name">Type Your Name: </label>
<input name="name" size="15" type="text" />
<label for="e-mail">Type Your E-mail: </label>
<input name="email" size="15" type="text" />
<label for="type">Subscription Type: </label>
<select name="type"><option>Weekly</option><option>Monthly</option></select>
<input name="submit" type="submit" value="Submit" />
 
FORM;
echo $form;
}
?&gt;

As seen above, storing a data on mysql is easy. First, a connection is established with mysql server, then a database is selected with mysql_select_db() function. The last thing is to execute the desired query using mysql_query() function.

What does addslashes do?
Prior to PHP 6, there was a feature called magic quotes that was created to help protect programmers from writing bad form processing code. Magic quotes automatically escapes from risky form data that might be used for SQL Injection with a backslash \. The characters escaped by PHP include: quote ‘, double quote “, backslash \ and NULL characters. In other words, a hacker, may type something in your form to reach your private SQL database. For instance; if you don’t use addslashes to add backslashes into the user written text, you might be hacked with this:

Hacker’s input:
username: hacker
password: ‘ OR 1

Your PHP Script:
mysql_query(”SELECT * FROM users WHERE username=’$username’ and password=’$password’”);

above code would be the following which always returns a row that will result the hacker log in
mysql_query(”SELECT * FROM users WHERE username=’hacker’ and password=” OR 1′”);

using addslashes, your query would be the following, which will not return any result
mysql_query(”SELECT * FROM users WHERE username=’hacker’ and password=’\’ OR 1\’”);

Subscribers.php
Our aim is to list all the subscribers in order with their information. We will sort them with their ids in subscribers.php. Therefore, we have to use the SELECT query which will select all the subscribers sorting with their ids. So, how do we output the results? It’s a little bit tricky. We first fetch the result into an associative array using the function: mysql_fetch_row(), and output the array using while loop.

$id : $name : $email : $type
LIST;
}
?&gt;

If we look closer, our mysql query has a “ORDER BY id ASC” part. This is to arrange the results in ascending order. Results, are assigned to an associative array. This array has 4 corresponding column results of mysql. For example, $row['name'], is assigned with a new value of ‘name’ column, depending on the index of $result, which is incremented at the beginning of every loop. Therefore, in every loop, a different row is printed with echo function using heredoc tool.

Stripslashes: Remember we added back slashes to escape from risky data before storing our data on mysql. So we use stripslashes function to remove added slashes.

Now, we’ll go further with our subscription system. Yes, we have a form for our users to subscribe our web site and we have a web page to see all our subscribers. Now, we’ll modify our subscribers.php to email our newsletter to each subscriber. Sounds good? Yes.

Mods to do:

  • A text box to write e-mail
  • A select box to select subscribers to mail
  • IF statement to check if form is submitted
  • Mail function inside while statement, one by one mailing
<label for="email">E-mail:</label><textarea cols="10" rows="6" name="email"></textarea>
  • Share/Save/Bookmark
Tags:

Leave Comment