How to Code PHP Part 2

Welcome to the second part of the How to Code PHP Tutorial. In this article I’ll show you the rest of the basics of using the PHP Engine. I’ll cover the following:

  • IF Statements
  • SWITCH Statements
  • FOR Loops
  • WHILE Loops
  • DO WHILE Loops
  • Including Files
  • Creating Functions
  • What Does Scope Mean?
  • Date and Time Functions
  • How to Send Email
  • Accessing Databases

After you read this tutorial, you will know how to code PHP. Then in those articles that follow I’ll provide you with real working PHP code that you can use to make your sites more dynamic.

IF Statements

Every language provides programmers with the capability to react differently based off of different conditions. With the PHP Engine you handle conditions using either the if than else, or switch statements. This is the format of an if condition handler:

if (condition) {

// Perform actions

} elseif (condition) {

// Perform actions

} else {

// Perform actions

}

The above if statements ask if a certain condition is true, perform all of the actions contained between the curly braces { }. If they are not, skip all of the actions and test to see if another condition is true. If that condition is also false then perform the last set of actions by default. Here is a real world example:

if (($age >= 45) && ($age <= 65)) {

echo “You are a Baby Boomer”;

} elseif (($age >= 25) && ($age <= 44)) {

echo “You are a Gen Xer’”;

} else {

echo “You are a member of Gen Y”;

}

Conditional & Logical Operators

There are 10 different operators you can use in PHP to test for different conditions. Here is the list:

  • = = : Equal to
  • != : Not Equal to
  • > : Greater than
  • < : Less than
  • >= : Greater than or equal to
  • <= : Less than or equal to
  • ! : Not : Placed before a condition to provide opposite results Ex: !(5>2), the conditional 5>2 would return a value of true and then ! Would convert the result to the value of false.
  • && : Logical And : Used to perform more complicated comparisons. Used to test that two or more conditions return a value of true, for the Logical And to return a value of true.
  • || : Logical Or : Used to perform more complicated comparisons. Used to test that one or another conditions return a value of true, for the Logical Or to return a value of true.

These conditional and logical operators are used not only for if statements, but also with switch, for, while and do while statements as you will see soon.

SWITCH Statement

If you must perform long if conditional tests, you may prefer to use a switch conditional test. The switch conditional test checks the value it is passed for equality to predefined values and then performs the most appropriate set of statements. Here is the basic format of a PHP switch statement:

switch ($variable_passed) {

case ‘value1’:

// Perform actions

break;

case ‘value2’:

// Perform actions

break;

default:

// Perform default actions

break;

}

Here you pass the switch statement a variable, no condition is performed within the brackets that proceed the switch keyword. Then we check if the value of that variable is equal to the value that proceeds the case statement. If it does, then the actions that follow are executed until the break statement is executed.

The Break statement moves execution of statements out of whatever loop that is currently executed. So if the above $variable value equals ‘value1’, then $variable will never be checked for equality to ‘value2’.

Another concept you have to understand about the switch statement is the keyword default. Here you are just defining the default action if the variable that was passed, didn’t equal any of the predefined values.

Here is a real world example on how you would use the switch statement with the PHP Engine:

switch ($number) {

case ‘1’:

echo “You entered the value 1”;

break;

case ‘2’:

case ‘3’:

echo “You entered the value 2 or 3”;

break;

default :

echo “You entered another value”;

break;

}

You see here how you could check for multiple values as well, through the use of stacking case statements like I did above for values of 2 or 3.

FOR Loops

Every programming language provides programmers with the ability to perform tasks repetitively as long as certain conditions are met. The PHP engine provides you with 4 looping tools, being the for, while, do-while loops and foreach.

Here is the basic structure of the for loop:

for( initialize variable; condition; iteration)

{

// Perform actions

}

Here is a real example of a for loop:

for( $i = 1; $i < =20; $i++)

{

echo “$i ”;

}

This code would print the numbers 1 thru 20 to the browser. To use a for loop you first type the keyword for. Inside of the brackets, you first have to create and assign a value to a variable, in this case $i. This value will be manipulated in some way to decide how long you will loop through the statements that lie between the curly braces. You see that we are going to add 1 to $i, each time we loop through, with the i++ shortcut. After we assign an initial value to $i, we define how long we will loop with some conditional statement. In this case til $i is less than or equal to 20.

While Loops

A while loop can be used in much the same way as the for loop. Here is it’s basic structure:

while(condition) {

// Perform actions

iteration;

}

Here is a real world example:

$i = 1;

while($i <= 20) {

echo “$i ”;

$i++;

}

This like the for loop, prints the numbers 1 thru 20 to the browser. To create a while loop you must define the conditions under which you will perform the actions between the curly braces { }. You can see the iterating statement $i++; is found with in the body of the loop. That’s about it.

Do While Loops

You would use a do while loop when you want to guarantee the statements within the curly braces are executed at least one time. This is guaranteed because the condition is checked after the first iteration. Here is the structure of a do while loop:

initialize variable;

do {

// Perform actions

iterator;

} while(condition);

Here is a real world example:

$i = 1;

do {

echo “$i ”;

$i++;

} while ($i <= 20);

Here we will first run through all of the statements between curly braces { }. The last statement iterates $i++. Then we check if the required conditions are being met and whether we should continue looping, with the statement while($i <= 20).

Including Files

Most of the time you will pull PHP code into your web pages instead of typing them in directly. The reason why is because over time you will reuse code you or others have written and you’ll also like to link to outside code for security and organizational reasons. When you include this outside code you are taking all the content of the included code and dropping it directly into your HTML code.

You can include code with the following two statements:

require_once(‘phpcode.php’); // Grabs and places code into web page

include_once(‘phpcode.php’); // Makes sure the code isn’t accidentally inserted more than once

Creating Functions

You’ve seen a lot of built in functions, now you’ll learn how to make your own. The basic structure is:

function function_name(arguments sent)

{

// Perform Actions

}

Here is a real world function:

function add_values($first_num, $second_num)

{

return ($first_num + $second_num);

}

This function accepts two variables. These variable names don’t have to match the variable names that lie outside of the function. The body of the function lies between curly braces { }. You can perform any actions inside of a function that you can perform outside of it.

You can return a value to the calling statement with the return statement. This function could have been called with a statement like these:

$addition = add_values($number_one, $number_two);

echo $number_one . “ + “. $number_two. “ = “. add_values($number_one, $number_two);

You can send any variable type to a function as long as you send them in the proper order. By creating default argument values, you have a safe guard you can use to make sure functions don’t throw an error. You can define default values like this: function($first_num=1, $second_num=1).

If you define default values and no arguments are sent the default values are used. If new arguments are sent then the default values are ignored.

What Does Scope Mean?

The variables you define within your functions are not available outside of your function body. This is what we mean when we talk about scope. You could actually use the same variable names inside and outside of your functions, but you might not want to do that if it causes confusion.

If you do have a variable that you want to be available through out all of your code define it as a global variable. You do that with the keyword global, like this: global $variable_name;.

Just so you know, a variable defined within a function is called a static variable. Add that to your jargon library.

Date and Time Functions

You can get a lot of information on the date and time with the PHP engine. The date function will return you this information and is of the structure:

date(‘date format’);

Here are the date codes available

  • Y: Year as 4 Digits
  • y: Year as 2 Digits
  • n: Month as One or Two Digits
  • F: Month’s Name
  • M: Month’s Name Abbreviated to Three Letters
  • d: Day of the Month as Two Digits
  • l: Day of the Week Name
  • D: Day of the Week’s Three Letter Name
  • g: Normal Hour as One or Two Digits
  • G: Military Hour as One or Two Digits
  • h: Normal Hour as Two Digits
  • H: Military Hour as Two Digits
  • i: minutes
  • s: Seconds
  • a: Returns am or pm
  • A: Returns AM or PM

Example date function:

echo date(‘g:i, l, F d, Y’); // Prints out ‘3:52, Monday, April 19, 2010

How to Send Email

In the next article I’ll cover how to process form data and then give you the example code behind sending mail. Here I’ll just describe the function and how to use it. Here is the basic format for the mail function:

mail ( $to, $subject, $body, $from, $replyto, $cc, $bcc);

You don’t need to enter values for reply-to, cc, or bcc. I’ll trust that you know how to use email and won’t go into what those codes mean. As long as your server is set up right, that is all you need to do to send an email. Also, if your server has a default email set, you won’t need to fill in a result for the from variable.

Accessing Databases

To end this article I’ll go over how to access and query a database. In future articles, I’ll cover common database code used with PHP.

Connecting to a MySQL Database

Before you can start querying a database you have to connect to it. Here is the code behind doing that:

$dbs = mysql_connect ($dbhost, $userid, $password) OR die(‘Couldn’t Connect to the Database: ‘ . mysql_error() );

You use the function mysql_connect to create a reference ($dbs) you can use to access the database. You have to pass it three variables being the host address of the database, the userid and password for the database. If the connection fails this will print out an error message. You can get the database host address from the hosting company your using.

Now that you have a reference for the database you have to signal that you want to use the database, much as you do with the USE command in SQL. Here is the Database SQL Tutorial if you forgot how to use SQL. You tell the database that you want to use it by calling the following statement:

@mysql_select_db(DB_NAME) or die(‘Couldn’t Select the Database: ‘ . mysql_error() );

You obviously want to keep the above information private so:

Make sure it is inaccessible privilege wise

Make sure it has the extension .php

Save it to a directory that is outside of the root directory

Access it with the require_once function. Ex. require_once(‘../mysql_connect.php’);

Executing Queries

Now your connected to your database, so I’ll go over how you can query the database. You can perform any query inside of PHP that you can using the SQL terminal. The standard structure of a query in PHP:

$query_result = mysql_query($query);

Normally it is common to assign a SQL query to a variable, in this case $query, and then send that query to the mysql_query function. Here is a real world example:

$query = “INSERT INTO customer(first_name, last_name) VALUES (‘Peekaboo’,’Kitty’)”;

$query_result = mysql_query($query);

Accessing the Results of Queries

When you query a database with these SQL statements: INSERT, DELETE, ALTER, or UPDATE, there is no value to return, so what is returned? If the query processed properly you receive the value true and false otherwise.

The mysql_fetch_array function is used to retrieve information when a query generates it. You need to pass the value of $query_result to this function inside of a while loop that will spit out one record after another until there are no more results. Here is an example:

while ($row = mysql_fetch_array($query_result)) {

// Perform actions with the data

}

You can access the value of row, which is an array, either by column name or by entering a number that represents the 1st through the number of total columns returned.

That’s All Folks

Well that is all for this article on PHP. I’ll provide code examples in the upcoming articles as well as handle Sessions and Cookies. If you have any questions leave them below.

Till Next Time

– Think Tank

Leave a Reply

Your email address will not be published.

Google+