Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,151,607 members, 7,812,996 topics. Date: Tuesday, 30 April 2024 at 02:30 AM

Php Class For Beginners. Question Will Be Treated With High Priority. - Webmasters - Nairaland

Nairaland Forum / Science/Technology / Webmasters / Php Class For Beginners. Question Will Be Treated With High Priority. (35159 Views)

How Should Archive And Label Pages Be Treated? / Blogging Advice For Beginners / Designing A Website: For Beginners (2) (3) (4)

(1) (2) (3) (4) (5) (6) (7) (8) (9) (10) ... (13) (Reply) (Go Down)

Php Class For Beginners. Question Will Be Treated With High Priority. by quadrillio(m): 3:35pm On Nov 10, 2008
After much noise of people who want to learn PHP. I will like to let them know that I have take it upon myself to teach it and I welcome any PHP Question


Lets Start

What Is PHP
PHP is a programming language that was designed for creating dynamic websites. It slots into your web server and processes instructions contained in a web page before that page is sent through to your web browser. Certain elements of the page can therefore be generated on-the-fly so that the page changes each time it is loaded. For instance, you can use PHP to show the current date and time at the top of each page in your site, as you'll see later in this lesson.

The name PHP is a recursive acronym that stands for PHP: Hypertext Preprocessor. It began life called PHP/FI, the "FI" part standing for Forms Interpreter. Though the name was shortened a while back, one of PHP's most powerful features is how easy it becomes to process data submitted in HTML forms. PHP can also talk to various database systems, giving you the ability to generate a web page based on a SQL query.

For example, you could enter a search keyword into a form field on a web page, query a database with this value, and produce a page of matching results. You will have seen this kind of application many times before, at virtually any online store as well as many websites that do not sell anything, such as search engines.

The PHP language is flexible and fairly forgiving, making it easy to learn even if you have not done any programming in the past. If you already know another language, you will almost certainly find similarities here. PHP looks like a cross between C, Perl, and Java, and if you are familiar with any of these, you will find that you can adapt your existing programming style to PHP with little effort.

[size=8pt][size=8pt]
Server-Side Scripting
[/size][/size]


The most important concept to learn when starting out with PHP is where exactly it fits into the grand scheme of things in a web environment. When you understand this, you will understand what PHP can and cannot do.

The PHP module attaches to your web server, telling it that files with a particular extension should be examined for PHP code. Any PHP code found in the page is executedwith any PHP code replaced by the output it producesbefore the web page is sent to the browser.

File Extensions The usual web server configuration is that somefile.php will be interpreted by PHP, whereas somefile.html will be passed straight through to the web browser, without PHP getting involved.


The only time the PHP interpreter is called upon to do something is when a web page is loaded. This could be when you click a link, submit a form, or just type in the URL of a web page. When the web browser has finished downloading the page, PHP plays no further part until your browser requests another page.

Because it is only possible to check the values entered in an HTML form when the submit button is clicked, PHP cannot be used to perform client-side validationin other words, to check that the value entered in one field meets certain criteria before allowing you to proceed to the next field. Client-side validation can be done using JavaScript, a language that runs inside the web browser itself, and JavaScript and PHP can be used together if that is the effect you require.

The beauty of PHP is that it does not rely on the web browser at all; your script will run the same way whatever browser you use. When writing server-side code, you do not need to worry about JavaScript being enabled or about compatibility with older browsers beyond the ability to display HTML that your script generates or is embedded in.

PHP Tags
Consider the following extract from a PHP-driven web page that displays the current date:

Today is <?php echo date('j F Y');?>


The <?php tag tells PHP that everything that follows is program code rather than HTML, until the closing ?> tag. In this example, the echo command tells PHP to display the next item to screen; the following date command produces a formatted version of the current date, containing the day, month, and year.

The Statement Terminator The semicolon character is used to indicate the end of a PHP command. In the previous examples, there is only one command, and the semicolon is not actually required, but it is good practice to always include it to show that a command is complete.


In this book PHP code appears inside tags that look like <?php , ?>. Other tag styles can be used, so you may come across other people's PHP code beginning with tags that look like <? (the short tag), <% (the ASP tag style) or <SCRIPT LANGUAGE="php"> (the script tag).

Of the different tag styles that can be used, only the full <?php tag and the script tag are always available. The others are turned off or on by using a PHP configuration setting. We will look at the php.ini configuration file in Lesson 23, "PHP Configuration."

Standard PHP Tags It is good practice to always use the <?php tag style so your code will run on any system that has PHP installed, with no additional configuration needed. If you are tempted to use <? as a shortcut, know that any time you move your code to another web server, you need to be sure it will understand this tag style.





Anything that is not enclosed in PHP tags is passed straight through to the browser, exactly as it appears in the script. Therefore, in the previous example, the text Today is appears before the generated date when the page is displayed.

end of todays lecture
Tomorrow is another Day
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by fluxdon(m): 9:01pm On Nov 10, 2008
ur philantropic gestures is laudable. i enjoyed d class. bt i wish i cud meet wit u f2f. thanks
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by quadrillio(m): 2:03pm On Nov 11, 2008
welcome to todays class!!

first I forgot to introduce myself in my last lesson.
My Name is Olawale Quadri, am a web developer.
you can call me on 08077796668 (for questions and assistance).

Okay, enough intros let go on with todays lecture.

by now I believe you have your php installed and your enviroment done.
in case you need PHP its free you can download it online ( or better still u can download XAMPP or WAMP)
google them(as a developer you need to know how to make little research like this onces)

Let start.
Go ahead and create a new file called time.php that contains Listing 1.1, in a location that can be accessed by a PHP-enabled web server. This is a slight variation on the date example shown previously.

Listing 1.1. Displaying the System Date and Time
The time is
<?php echo date('H:i:s');?>
and the date is
<?php echo date('j F Y');?>



When you enter the URL to this file in your web browser, you should see the current date and time, according to the system clock on your web server, displayed.

Running PHP Locally If you are running PHP from your local PC, PHP code in a script will be executed only if it is accessed through a web server that has the PHP module enabled. If you open a local script directly in the web browserfor instance, by double-clicking or dragging and dropping the file into the browserit will be treated as HTML only.





Web Document Location If you were using a default Apache installation in Windows, you would create time.php in the folder C:\Program Files\Apache Group\Apache\htdocs, and the correct URL would be http://localhost/time.php.





If you entered Listing 1.1 exactly as shown, you might notice that the actual output produced could be formatted a little betterthere is no space between the time and the word and. Any line in a script that only contains code inside PHP tags will not take up a line of output in the generated HTML.

If you use the View Source option in your web browser, you can see the exact output produced by your script, which should look similar to the following:

The time is
15:33:09and the date is
13 October 2004



If you insert a space character after ?>, that line now contains non-PHP elements, and the output is spaced correctly.

The echo Command
While PHP is great for embedding small, dynamic elements inside a web page, in fact the whole page could consist of a set of PHP instructions to generate the output if the entire script were enclosed in PHP tags.

The echo command is used to send output to the browser. Listing 1.1 uses echo to display the result of the date command, which returns a string that contains a formatted version of the current date. Listing 1.2 does the same thing but uses a series of echo commands in a single block of PHP code to display the date and time.

Listing 1.2. Using echo to Send Output to the Browser
<?php
echo "The time is ";
echo date('H:i:s');
echo " and the date is ";
echo date('j F Y');
?>



The non-dynamic text elements you want to output are contained in quotation marks. Either double quotes (as used in Listing 1.2) or single quotes (the same character used for an apostrophe) can be used to enclose text strings, although you will see an important difference between the two styles in Lesson 2, "Variables." The following statements are equally valid:

echo "The time is ";
echo 'The time is ';



Notice that space characters are used in these statements inside the quotation marks to ensure that the output from date is spaced away from the surrounding text. In fact the output from Listing 1.2 is slightly different from that for Listing 1.1, but in a web browser you will need to use View Source to see the difference. The raw output from Listing 1.2 is as follows:

The time is 15:59:50 and the date is 13 October 2004



There are no line breaks in the page source produced this time. In a web browser, the output looks just the same as for Listing 1.1 because in HTML all whitespace, including carriage returns and multiple space or tab characters, is displayed as a single space in a rendered web page.

A newline character inside a PHP code block does not form part of the output. Line breaks can be used to format the code in a readable way, but several short commands could appear on the same line of code, or a long command could span several linesthat's why you use the semicolon to indicate the end of a command.

Listing 1.3 is identical to Listing 1.2 except that the formatting makes this script almost unreadable.

Listing 1.3. A Badly Formatted Script That Displays the Date and Time
<?php echo "The time is ";  echo date('H:i:s'); echo
" and the date is "
; echo date(
'j F Y'
);
?>



Using Newlines If you wanted to send an explicit newline character to the web browser, you could use the character sequence \n. There are several character sequences like this that have special meanings, and you will see more of them in Lesson 6, "Working with Strings."





Comments
Another way to make sure your code remains readable is by adding comments to it. A comment is a piece of free text that can appear anywhere in a script and is completely ignored by PHP. The different comment styles supported by PHP are shown in Table 1.1.

Comment Styles in PHP Comment & Description

// or #
Single-line comment. Everything to the end of the current line is ignored.

/* ,  */
Single- or multiple-line comment. Everything between /* and */ is ignored.





Listing 1.4 produces the same formatted date and time as Listings 1.1, 1.2, and 1.3, but it contains an abundance of comments. Because the comments are just ignored by PHP, the output produced consists of only the date and time.

Listing 1.4. Using Comments in a Script
<?php
/* time.php
   This script prints the current date
   and time in the web browser
*/

echo "The time is ";
echo date('H:i:s');  // Hours, minutes, seconds

echo " and the date is ";
echo date('j F Y');  // Day name, month name, year
?>

Listing 1.4 includes a header comment block that contains the filename and a brief description, as well as inline comments that show what each date command will produce.

In the lessons so far you have learned how PHP works in a web environment, and you have seen what a simple PHP script looks like. In the next lesson you will learn how to use variables.

See you tomorrow.
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by Ehikoyia: 11:02pm On Nov 11, 2008
thank you for the tutorials
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by Ehikoyia: 11:03pm On Nov 11, 2008
thank you for the tutorials
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by quadrillio(m): 11:38am On Nov 12, 2008
Welcome today,

NB: incase you have any problem (about installation or tutorial) please post it so that it can be treated. Everybody is here to learn.

Understanding Variables

Variablescontainers in which values can be stored and later retrievedare a fundamental building block of any programming language.

For instance, you could have a variable called number that holds the value 5 or a variable called name that holds the value Chris. The following PHP code declares variables with those names and values:

$number = 5;
$name = "Chris";



In PHP, a variable name is always prefixed with a dollar sign. If you remember that, declaring a new variable is very easy: You just use an equals symbol with the variable name on the left and the value you want it to take on the right.

Declaring Variables Unlike in some programming languages, in PHP variables do not need to be declared before they can be used. You can assign a value to a new variable name any time you want to start using it.





Variables can be used in place of fixed values throughout the PHP language. The following example uses echo to display the value stored in a variable in the same way that you would display a piece of fixed text:

$name = "Chris";
echo "Hello, ";
echo $name;


The output produced is
Hello, Chris



Naming Variables
The more descriptive your variable names are, the more easily you will remember what they are used for when you come back to a script several months after you write it.

It is not usually a good idea to call your variables $a, $b, and so on. You probably won't remember what each letter stood for, if anything, for long. Good variable names tell exactly what kind of value you can expect to find stored in them (for example, $price or $name).

Case-Sensitivity Variable names in PHP are case-sensitive. For example, $name is a different variable than $Name, and the two could store different values in the same script.





Variable names can contain only letters, numbers, and the underscore character, and each must begin with a letter or underscore. below shows some examples of valid and invalid variable names.

Examples of Valid and Invalid Variable Names

Valid Variable Names Invalid Variable Names

$percent $pct%


$first_name $first-name

$line_2 $2nd_line





Using Underscores Using the underscore character is a handy way to give a variable a name that is made up of two or more words. For example $first_name and $date_of_birth are more readable for having underscores in place.

Another popular convention for combining words is to capitalize the first letter of each wordfor example, $FirstName and $DateOfBirth. If you prefer this style, feel free to use it in your scripts but remember that the capitalization does matter.





Expressions
When a variable assignment takes place, the value given does not have to be a fixed value. It could be an expressiontwo or more values combined using an operator to produce a result. It should be fairly obvious how the following example works, but the following text breaks it down into its components:

$sum = 16 + 30;
echo $sum;



The variable $sum takes the value of the expression to the right of the equals sign. The values 16 and 30 are combined using the addition operatorthe plus symbol (+)and the result of adding the two values together is returned. As expected, this piece of code displays the value 46.

To show that variables can be used in place of fixed values, you can perform the same addition operation on two variables:

$a = 16;
$b = 30;
$sum = $a + $b;
echo $sum;



The values of $a and $b are added together, and once again, the output produced is 46.

Variables in Strings
You have already seen that text strings need to be enclosed in quotation marks and learned that there is a difference between single and double quotes.

The difference is that a dollar sign in a double-quoted string indicates that the current value of that variable should become part of the string. In a single-quoted string, on the other hand, the dollar sign is treated as a literal character, and no reference is made to any variables.

The following examples should help explain this. In the following example, the value of variable $name is included in the string:

$name = "Chris";
echo "Hello, $name";



This code displays Hello, Chris.

In the following example, this time the dollar sign is treated as a literal, and no variable substitution takes place:

$name = 'Chris';
echo 'Hello, $name';



This code displays Hello, $name.

Sometimes you need to indicate to PHP exactly where a variable starts and ends. You do this by using curly brackets, or braces ({}). If you wanted to display a weight value with a suffix to indicate pounds or ounces, the statement might look like this:

echo "The total weight is {$weight}lb";



If you did not use the braces around $weight, PHP would try to find the value of $weightlb, which probably does not exist in your script.

You could do the same thing by using the concatenation operator, the period symbol, which can be used to join two or more strings together, as shown in the following example:

echo 'The total weight is ' . $weight . 'lb';



The three valuestwo fixed strings and the variable $weightare simply stuck together in the order in which they appear in the statement. Notice that a space is included at the end of the first string because you want the value of $weight to be joined to the word is.

If $weight has a value of 99, this statement will produce the following output:

The total weight is 99lb


See you tomorrow
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by quadrillio(m): 12:50pm On Nov 14, 2008
Hello, I stumbled on this tread on PHP

https://www.nairaland.com/nigeria/topic-191707.32.html

I just to ask you fellow nairalanders

Should I continue or I should collabo with the guy cos am asking him.

or what do you think

so that I can continue.
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by Mustay(m): 2:21pm On Nov 14, 2008
Dates of starting both topics are dissimilar
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by quadrillio(m): 10:27am On Nov 17, 2008
Welcome back, I have decided to continue

so that everyone can have a two way of learn PHP.

let's start.

Data Types

Every variable that holds a value also has a data type that defines what kind of value it is holding. The basic data types in PHP are shown in Table 2.2.

Table 2.2. PHP Data Types Data Type & Description

Boolean - A truth value; can be either TRUE or FALSE.

Integer - A number value; can be a positive or negative whole number.

Double (or float) - A floating-point number value; can be any decimal number.

String - An alphanumeric value; can contain any number of ASCII characters.





When you assign a value to a variable, the data type of the variable is also set. PHP determines the data type automatically, based on the value you assign. If you want to check what data type PHP thinks a value is, you can use the gettype function.

Running the following code shows that the data type of a decimal number is double:

$value = 7.2;
echo gettype($value);



The complementary function to gettype is settype, which allows you to override the data type of a variable. If the stored value is not suitable to be stored in the new type, it will be modified to the closest value possible.

The following code attempts to convert a string value into an integer:

$value = "22nd January 2005";
settype($value, "integer"wink;
echo $value;



In this case, the string begins with numbers, but the whole string is not an integer. The conversion converts everything up to the first nonnumeric character and discards the rest, so the output produced is just the number 22.

Analyzing Data Types In practice, you will not use settype and gettype very often because you will rarely need to alter the data type of a variable. This book covers this topic early on so that you are aware that PHP does assign a data type to every variable.





Type Juggling
Sometimes PHP will perform an implicit data type conversion if values are expected to be of a particular type. This is known as type juggling.

For example, the addition operator expects to sit between two numbers. String type values are converted to double or integer before the operation is performed, so the following addition produces an integer result:

echo 100 + "10 inches";



This expression adds 100 and 10, and it displays the result 110.

A similar thing happens when a string operator is used on numeric data. If you perform a string operation on a numeric type, the numeric value is converted to a string first. In fact, you already saw this earlier in this lesson, with the concatenation operatorthe value of $weight that was displayed was numeric.

The result of a string operation will always be a string data type, even if it looks like a number. The following example produces the result 69, butas gettype shows$number contains a string value:

$number = 6 . 9;
echo $number;
echo gettype(6 . 9);



We will look at the powerful range of operators that are related to numeric and string data types in PHP in Lessons 5, "Working with Numbers," and 6, "Working with Strings."

Variable Variables
It is possible to use the value stored in a variable as the name of another variable. If this sounds confusing, the following example might help:

$my_age = 21;
$varname = "my_age";
echo "The value of $varname is ${$varname}";


The output produced is
The value of my_age is 21



Because this string is enclosed in double quotes, a dollar sign indicates that a variable's value should become part of the string. The construct ${$varname} indicates that the value of the variable named in $varname should become part of the string and is known as a variable variable.

The braces around $varname are used to indicate that it should be referenced first; they are required in double-quoted strings but are otherwise optional. The following example produces the same output as the preceding example, using the concatenation operator:

echo 'The value of ' . $varname . ' is ' . $$varname;


See you in the next class.
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by bug24(m): 12:50pm On Nov 17, 2008
hmmm, this is something some over-money conscious Nigerians wulda asked that they be paid to give this kinda selfless service.

@ Quadrillio,
Jah be with you as you pass ur knowledge across.
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by Nobody: 5:56am On Nov 18, 2008
Quadrillo, thanks so much for the class. Can you give like exercises/small projects at the end of each class so i can work on to strengthen my knowledge? Thanks. Also if you get MSN/AIM abeg PM Me with am, I want to speak to you ASAP. Thanks.
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by quadrillio(m): 4:28pm On Nov 19, 2008
Olasile_F:

Quadrillo, thanks so much for the class. Can you give like exercises/small projects at the end of each class so i can work on to strengthen my knowledge? Thanks. Also if you get MSN/AIM abeg PM Me with am, I want to speak to you ASAP. Thanks.

I plan to start giving out exercises after my last tenth lecture. and to give out a project after the whole class. by then my joy will be filled that I have accomplished my GOAL(which is to impact positively on everyone that knows me).

My yahoo id is quadri20_wale [at] yahoo.com. just in case you will like to talk, am always online(only when network dey Bleep up).

okay let start,

sorry for the break, it was due to a Nairalander who asked me to fixed a script for him. which is now done.

In the last lesson you have learned how variables work in PHP. In the next lesson you will see how to use conditional and looping statements to control the flow of your script. we'll look at two types of flow control: conditional statements, which tell your script to execute a section of code only if certain criteria are met, and loops, which indicate a block of code that is to be repeated a number of times.

Conditional Statements
A conditional statement in PHP begins with the keyword if, followed by a condition in parentheses. The following example checks whether the value of the variable $number is less than 10, and the echo statement displays its message only if this is the case:

$number = 5;
if ($number < 10) {
echo "$number is less than ten";
}



The condition $number < 10 is satisfied if the value on the left of the < symbol is smaller than the value on the right. If this condition holds true, then the code in the following set of braces will be executed; otherwise, the script jumps to the next statement after the closing brace.

Boolean Values Every conditional expression evaluates to a Boolean value, and an if statement simply acts on a trUE or FALSE value to determine whether the next block of code should be executed. Any zero value in PHP is considered FALSE, and any nonzero value is considered trUE.





As it stands, the previous example will be trUE because 5 is less than 10, so the statement in braces is executed, and the corresponding output is displayed. Now, if you change the initial value of $number to 10 or higher and rerun the script, the condition fails, and no output is produced.

Braces are used in PHP to group blocks of code together. In a conditional statement, they surround the section of code that is to be executed if the preceding condition is true.

Brackets and Braces You will come across three types of brackets when writing PHP scripts. The most commonly used terminology for each type is parentheses (()), braces ({}), and square brackets ([]).





Braces are not required after an if statement. If they are omitted, the following single statement is executed if the condition is true. Any subsequent statements are executed, regardless of the status of the conditional.

Braces and Indentation Although how your code is indented makes no difference to PHP, it is customary to indent blocks of code inside braces with a few space characters to visually separate that block from other statements.

Even if you only want a condition or loop to apply to one statement, it is still useful to use braces for clarity. It is particularly important in order to keep things readable when you're nesting multiple constructs.





Conditional Operators
PHP allows you to perform a number of different comparisons, to check for the equality or relative size of two values. PHP's conditional operators are shown in Table 3.1.

Table 3.1. Conditional Operators in PHP

Operator Description
== Is equal to

=== Is identical to (is equal and is the same data type)

!= Is not equal to

!== Is not identical to

< Is less than

<= Is less than or equal to

> Is greater than

>= Is greater than or equal to



= or ==? Be careful when comparing for equality to use a double equals symbol (==). A single = is always an assignment operator and, unless the value assigned is zero, your condition will always return trueand remember that TRUE is any nonzero value. Always use == when comparing two values to avoid headaches.





Logical Operators
You can combine multiple expressions to check two or more criteria in a single conditional statement. For example, the following statement checks whether the value of $number is between 5 and 10:

$number = 8;
if ($number >= 5 and $number <= 10) {
echo "$number is between five and ten";
}



The keyword and is a logical operator, which signifies that the overall condition will be true only if the expressions on either side are true. That is, $number has to be both greater than or equal to 5 and less than or equal to 10.

Table 3.2 shows the logical operators that can be used in PHP.

Table 3.2. Logical Operators in PHP Operator
Name Description

!a NOT True if a is not true

a && b AND True if both a and b are true

a || b OR True if either a or b is true

a and b AND True if both a and b are true

a xor b XOR True if a or b is true, but not both

a or b OR True if either a or b is true


You may have noticed that there are two different ways of performing a logical AND or OR in PHP. The difference between and and && (and between or and ||) is the precedence used to evaluate expressions.

Table 3.2 lists the highest-precedence operators first. The following conditions, which appear to do the same thing, are subtly but significantly different:

a or b and c
a || b and c



In the former condition, the and takes precedence and is evaluated first. The overall condition is true if a is true or if both b and c are true.

In the latter condition, the || takes precedence, so c must be true, as must either a or b, to satisfy the condition.

Operator Symbols Note that the logical AND and OR operators are the double symbols && and ||, respectively. These symbols, when used singularly, have a different meaning, as you will see in Lesson 5, "Working with Numbers."





Multiple Condition Branches
By using an else clause with an if statement, you can specify an alternate action to be taken if the condition is not met. The following example tests the value of $number and displays a message that says whether it is greater than or less than 10:

$number = 16;
if ($number < 10) {
echo "$number is less than ten";
}
else {
echo "$number is more than ten";
}



The else clause provides an either/or mechanism for conditional statements. To add more branches to a conditional statement, the elseif keyword can be used to add a further condition that is checked only if the previous condition in the statement fails.

The following example uses the date function to find the current time of daydate("H"wink gives a number between 0 and 23 that represents the hour on the clockand displays an appropriate greeting:

$hour = date("H"wink;
if ($hour < 12) {
echo "Good morning";
}
elseif ($hour < 17) {
echo "Good afternoon";
}
else {
echo "Good evening";
}



This code displays Good morning if the server time is between midnight and 11:59, Good afternoon from midday to 4:59 p.m., and Good evening from 5 p.m. onward.

Notice that the elseif condition only checks that $hour is less than 17 (5 p.m.). It does not need to check that the value is between 12 and 17 because the initial if condition ensures that PHP will not get as far as the elseif if $hour is less than 12.

The code in the else clause is executed if all else fails. For values of $hour that are 17 or higher, neither the if nor the elseif condition will be true.

elseif Versus else if In PHP you can also write elseif as two words: else if. The way PHP interprets this variation is slightly different, but its behavior is exactly the same.





The switch Statement
An if statement can contain as many elseif clauses as you need, but including many of these clauses can often create cumbersome code, and an alternative is available. switch is a conditional statement that can have multiple branches in a much more compact format.

The following example uses a switch statement to check $name against two lists to see whether it belongs to a friend:

switch ($name) {
case "Damon":
case "Shelley":
echo "Welcome, $name, you are my friend";
break;
case "Adolf":
case "Saddam":
echo "You are no friend of mine, $name";
break;
default:
echo "I do not know who you are, $name";
}



Each case statement defines a value for which the next block of PHP code will be executed. If you assign your first name to $name and run this script, you will be greeted as a friend if your name is Damon or Shelley, and you will be told that you are not a friend if your name is either Adolf or Saddam. If you have any other name, the script will tell you it does not know who you are.

There can be any number of case statements preceding the PHP code to which they relate. If the value that is being tested by the switch statement (in this case $name) matches any one of them, any subsequent PHP code will be executed until a break command is reached.

Breaking Out The break statement is important in a switch statement. When a case statement has been matched, any PHP code that follows will be executedeven if there is another case statement checking for a different value. This behavior can sometimes be useful, but mostly it is not what you wantso remember to put a break after every case.





Any other value for $name will cause the default code block to be executed. As with an else clause, default is optional and supplies an action to be taken if nothing else is appropriate.
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by Nobody: 6:03pm On Nov 19, 2008
Well Done Oh!!!!!!! grin grin cheesy
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by quadrillio(m): 1:37pm On Nov 20, 2008
Today, we take on loops. and happy to infom you that the that there will be a task at the end od this tutorial.


Loops
PHP offers three types of loop constructs that all do the same thingrepeat a section of code a number of timesin slightly different ways.

The while Loop
The while keyword takes a condition in parentheses, and the code block that follows is repeated while that condition is true. If the condition is false initially, the code block will not be repeated at all.

Infinite Loops The repeating code must perform some action that affects the condition in such a way that the loop condition will eventually no longer be met; otherwise, the loop will repeat forever.





The following example uses a while loop to display the square numbers from 1 to 10:

$count = 1;
while ($count <= 10) {
$square = $count * $count;
echo "$count squared is $square <br>";
$count++;
}



The counter variable $count is initialized with a value of 1. The while loop calculates the square of that number and displays it, then adds one to the value of $count. The ++ operator adds one to the value of the variable that precedes it.

The loop repeats while the condition $count <= 10 is true, so the first 10 numbers and their squares are displayed in turn, and then the loop ends.

The do Loop
The do loop is very similar to the while loop except that the condition comes after the block of repeating code. Because of this variation, the loop code is always executed at least onceeven if the condition is initially false.

The following do loop is equivalent to the previous example, displaying the numbers from 1 to 10, with their squares:

$count = 1;
do {
$square = $count * $count;
echo "$count squared is $square <br>";
$count++;
} while ($count <= 10);



The for Loop
The for loop provides a compact way to create a loop. The following example performs the same loop as the previous two examples:

for ($count = 1; $count <= 10; $count++) {
$square = $count * $count;
echo "$count squared is $square <br>";
}



As you can see, using for allows you to use much less code to do the same thing as with while and do.

A for statement has three parts, separated by semicolons:

The first part is an expression that is evaluated once when the loop begins. In the preceding example, you initialized the value of $count.

The second part is the condition. While the condition is true, the loop continues repeating. As with a while loop, if the condition is false to start with, the following code block is not executed at all.

The third part is an expression that is evaluated once at the end of each pass of the loop. In the previous example, $count is incremented after each line of the output is displayed.

Nesting Conditions and Loops
So far you have only seen simple examples of conditions and loops. However, you can nest these constructs within each other to create some quite complex rules to control the flow of a script.

Remember to Indent The more complex the flow control in your script is, the more important it becomes to indent your code to make it clear which blocks of code correspond to which constructs.





Breaking Out of a Loop
You have already learned about using the keyword break in a switch statement. You can also use break in a loop construct to tell PHP to immediately exit the loop and continue with the rest of the script.

The continue keyword is used to end the current pass of a loop. However, unlike with break, the script jumps back to the top of the same loop and continues execution until the loop condition fails.

The Task
=======
1, with your experience with loops, creata a multiplication table from 2 to 25
e.g.

2 time 1 =2
2 time 2= 4
,
,
, (till)
2 times 12 =24

3 times 1 =3
3 times 2=6 (to 25)

2, display the even number between 1 to 100;


NB please paste your code here so that everyone can learn.

See ya
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by Nobody: 9:19pm On Nov 21, 2008
Im working on the project. Thanks Quadrillo bro, I added you to YIM. Please accept my friend request
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by eliteweb(m): 9:42pm On Nov 23, 2008
@quad, Bravo!!! Wonderful job.
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by quadrillio(m): 3:50pm On Nov 24, 2008
am waiting for the result
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by quadrillio(m): 3:09pm On Nov 25, 2008
I decided to continue the lecture while I wait for the answer to my exercise.

In the last lesson you have learned how to vary the flow of your PHP script by using conditional statements and loops. In this next lesson you will see how to create reusable functions from blocks of PHP code.

In this lesson you will learn how frequently used sections of code can be turned into reusable functions.

Using Functions

A function is used to make a task that might consist of many lines of code into a routine that can be called using a single instruction.

PHP contains many functions that perform a wide range of useful tasks. Some are built in to the PHP language; others are more specialized and are available only if certain extensions are activated when PHP is installed.

The online PHP manual (www.php.net) is an invaluable reference. As well as documentation for every function in the language, the manual pages are also annotated with user-submitted tips and examples, and you can even submit your own comments if you want.

Online Reference To quickly pull up the PHP manual page for any function, use this shortcut: www.php.net/function_name.





You have already used the date function to generate a string that contains a formatted version of the current date. Let's take a closer look at how that example from Lesson 1, "Getting to Know PHP," works. The example looked like this:

echo date('j F Y');



The online PHP manual gives the prototype for date as follows:

string date (string format [, int timestamp])



This means that date takes a string argument called format and, optionally, the integer timestamp. It returns a string value. This example sends j F Y to the function as the format argument, but timestamp is omitted. The echo command displays the string that is returned.

Prototypes Every function has a prototype that defines how many arguments it takes, the arguments' data types, and what value is returned. Optional arguments are shown in square brackets ([]).





Defining Functions
In addition to the built-in functions, PHP allows you to define your own. There are advantages to using your own function. Not only do you have to type less when the same piece of code has to be executed several times but a custom-defined function also makes your script easier to maintain. If you want to change the way a task is performed, you only need to update the program code oncein the function definitionrather than fix it every place it appears in your script.

Modular Code Grouping tasks into functions is the first step toward modularizing your codesomething that is especially important to keep your scripts manageable as they grow in size and become more complex.





The following is a simple example that shows how a function is defined and used in PHP:

function add_tax($amount) {
$total = $amount * 1.09;
return $total;
}

$price = 16.00;
echo "Price before tax: $price <br>";
echo "Price after tax: ";
echo add_tax($price);



The function keyword defines a function called add_tax that will execute the code block that follows. The code that makes up a function is always contained in braces. Putting $amount in parentheses after the function name stipulates that add_tax takes a single argument that will be stored in a variable called $amount inside the function.

The first line of the function code is a simple calculation that multiplies $amount by 1.09which is equivalent to adding 9% to that valueand assigns the result to $total. The return keyword is followed by the value that is to be returned when the function is called from within the script.

Running this example produces the following output:

Price before tax: 16
Price after tax: 17.44



This is an example of a function that you might use in many places in a web page; for instance, on a page that lists all the products available in an online store, you would call this function once for each item that is displayed to show the after-tax price. If the rate of tax changes, you only need to change the formula in add_tax to alter every price displayed on that page.
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by quadrillio(m): 3:54pm On Dec 01, 2008
Today it's,
Arguments and Return Values

Every function call consists of the function name followed by a list of arguments in parentheses. If there is more than one argument, the list items are separated with commas. Some functions do not require any arguments at all, but a pair of parentheses is still requiredeven if there are no arguments contained in them.

The built-in function phpinfo generates a web page that contains a lot of information about the PHP module. This function does not require any arguments, so it can be called from a script that is as simple as

<?php phpinfo();?>



If you create this script and point a web browser at it, you will see a web page that contains system information and configuration settings.

Returning Success or Failure
Because phpinfo generates its own output, you do not need to prefix it with echo, but, for the same reason, you cannot assign the web page it produces to a variable. In fact, the return value from phpinfo is the integer value 1.

Returning True and False Functions that do not have an explicit return value usually use a return code to indicate whether their operation has completed successfully. A zero value (FALSE) indicates failure, and a nonzero value (TRUE) indicates success.





The following example uses the mail function to attempt to send an email from a PHP script. The first three arguments to mail specify the recipient's email address, the message subject, and the message body. The return value of mail is used in an if condition to check whether the function was successful:

if (mail("chris@lightwood.net",
"Hello", "This is a test email"wink) {
echo "Email was sent successfully";
}
else {
echo "Email could not be sent";
}



If the web server that this script is run on is not properly configured to send email, or if there is some other error when trying to send, mail will return zero, indicating that the email could not be sent. A nonzero value indicates that the message was handed off to your mail server for sending.

Return Values Although you will not always need to test the return value of every function, you should be aware that every function in PHP does return some value.





Default Argument Values
The mail function is an example of a function that takes multiple arguments; the recipient, subject, and message body are all required. The prototype for mail also specifies that this function can take an optional fourth argument, which can contain additional mail headers.

Calling mail with too few arguments results in a warning. For instance, a script that contains the following:

mail("chris@lightwood.net", "Hello"wink;



will produce a warning similar to this:

Warning: mail() expects at least 3 parameters, 2 given in
/home/chris/mail.php on line 3



However, the following two calls to mail are both valid:

mail("chris@lightwood.net", "Hello", "This is a test email"wink;

mail("chris@lightwood.net", "Hello", "This is a test email",
"Cc: editor@samspublishing.com"wink;



To have more than one argument in your own function, you simply use a comma-separated list of variable names in the function definition. To make one of these arguments optional, you assign it a default value in the argument list, the same way you would assign a value to a variable.

The following example is a variation of add_tax that takes two argumentsthe net amount and the tax rate to add on. $rate has a default value of 10, so it is an optional argument:

function add_tax_rate($amount, $rate=10) {
$total = $amount * (1 + ($rate / 100));
return($total);
}



Using this function, the following two calls are both valid:

add_tax_rate(16);
add_tax_rate(16, 9);



The first example uses the default rate of 10%, whereas the second example specifies a rate of 9% to be usedproducing the same behavior as the original add_tax function example.

Optional Arguments All the optional arguments to a function must appear at the end of the argument list, with the required values passed in first. Otherwise, PHP will not know which arguments you are passing to the function.





Variable Scope
The reason values have to be passed in to functions as arguments has to do with variable scopethe rules that determine what sections of script are able to access which variables.

The basic rule is that any variables defined in the main body of the script cannot be used inside a function. Likewise, any variables used inside a function cannot be seen by the main script.

Scope Variables available within a function are said to be local variables or that their scope is local to that function. Variables that are not local are called global variables.

Local and global variables can have the same name and contain different values, although it is best to try to avoid this to make your script easier to read.





When called, add_tax calculates $total, and this is the value returned. However, even after add_tax is called, the local variable $total is undefined outside that function.

The following piece of code attempts to display the value of a global variable from inside a function:

function display_value() {
echo $value;
}

$value = 125;
display_value();



If you run this script, you will see that no output is produced because $value has not been declared in the local scope.

To access a global variable inside a function, you must use the global keyword at the top of the function code. Doing so overrides the scope of that variable so that it can be read and altered within the function. The following code shows an example:

function change_value() {
global $value;
echo "Before: $value <br>";
$value = $value * 2;
}
$value = 100;
display_value();
echo "After: $value <br>";



The value of $value can now be accessed inside the function, so the output produced is as follows:

Before: 100
After: 200
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by Muza(m): 12:50am On Dec 04, 2008
thank God for copy and paste grin
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by quadrillio(m): 2:49pm On Dec 04, 2008
you expect me to do all this without reference to books abi

MR MUSA THE GURU CAN YOU START YOURS MAYBE YOU NO GO COPY FROM BOOK,

by the way, you suppose try solve the exercise, then we can talk.

Almighty Guru Musa.

or if you have an alternative let all nairalanders hear
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by yawatide(f): 3:52pm On Dec 04, 2008
quad,

I appreciate and commend your efforts here, I really do. I however will agre with Musa (without the smart ass attitude).

If indeed you are getting all this from a book, you should at least reference it. For one, you don't get someone accusing you of plagiarism. Two, you might as well upload the book here or email it to people and then let them come back to you or this post and ask any questions they may have.

Sure, given that most books are at least 50% fluff, it is good to condense it for people in need. Having said that, I think a reference to any book(s) is in order.

Once again, kudos on your gallant efforts.
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by rapattorny: 1:26am On Dec 09, 2008
Hey quadrillo,pls continue yr stuff i really love it,it's helping me learn php,meanwhile programs for yr exercises are

FOR EXERCISE 2

<?php

$count = 1;

while ($count <=50 )

{
$num=$count - 1;
$ans=$num * 2;
echo "even numbers btw 0 and 100 are $ans <br>";
$count++ ;
}

?>


FOR EXERCISE 1 WE HAVE

<?php


$count = 1;
while ($count <= 12) {
$mul = $count * 2;
echo " $count multiplied by 2 is $mul <br>";
$count++;
}

echo "<br>";

?>

<?php


$count = 1;
while ($count <= 12) {
$mul = $count * 3;
echo " $count multiplied by 3 is $mul <br>";
$count++;
}

echo "<br>";

?>


Pls continue yr wrk.
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by quadrillio(m): 11:45am On Dec 15, 2008
yawa-ti-de:

quad,

I appreciate and commend your efforts here, I really do. I however will agre with Musa (without the smart ass attitude).

If indeed you are getting all this from a book, you should at least reference it. For one, you don't get someone accusing you of plagiarism. Two, you might as well upload the book here or email it to people and then let them come back to you or this post and ask any questions they may have.

Sure, given that most books are at least 50% fluff, it is good to condense it for people in need. Having said that, I think a reference to any book(s) is in order.

Once again, kudos on your gallant efforts.
I get your point, and for this reason I want everyone who is interested in the book to drop there email address and it will be forwarded to there box.


@ rapattorny

I'll get back to you.
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by rapattorny: 11:08pm On Dec 16, 2008
Hey quad,my email is roe9000@yahoo.co.uk,pls drop any stuff u wanna and continue yr lessons i really need am,just continue doing yr stuff.Nice work.
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by quadrillio(m): 1:41pm On Dec 17, 2008
I will continue tomorrow. Thanks everybody.
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by Mustay(m): 10:01am On Dec 18, 2008
After seeing the tax rate function, I was so sure I had seen this somewhere before.

quadrillio:

I get your point, and for this reason I want everyone who is interested in the book to drop there email address and it will be forwarded to there box.

Methinks what yawa meant was that you acknowledge the original writer; even if it was Quadrillo cool wink
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by OmniPotens(m): 4:36pm On Dec 18, 2008
To make things easier here, folks, if you want to get faster in this PHP thing, send me a mail and I'll post a good ebook to you.


Cheers!
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by OmniPotens(m): 1:52am On Dec 19, 2008
Please, no one should post his/her email addresses here and expect me to come find it here then mail the ebook. If you don't know where to find my email address, kindly click at my username, there, you'll see my email address. That's how to find user's email addresses.

@manifest09
Send me an email and you'll get the book emailed to you. Don't post your email address here again.

Hope none programmers use this opportunity to get into the the beginners level in the programming world.

Cheers.
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by quadrillio(m): 5:31pm On Dec 23, 2008
Thanks guy, my mind can rest now, my aim is to pass the knowledge of PHP to everyone.

so if you guy can help. its very much allowed

Thanks and bye
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by OmniPotens(m): 6:38pm On Dec 23, 2008
quadrillio:

Thanks guy, my mind can rest now, my aim is to pass the knowledge of PHP to everyone.

so if you guy can help. its very much allowed

Thanks and bye

Are you saying you are no longer continuing your tutorials? If you are tied up, why not upload the book somewhere so they go download it there. Though the chunk by chunk method you are using here is just good enough.

Waiting to know what decision you are taking.
Re: Php Class For Beginners. Question Will Be Treated With High Priority. by Nobody: 9:37pm On Dec 23, 2008
@poster, Outstanding, I am Tony Ogundipe, a freelance software programmer and website developer.
I cover from html through css, javascript, php and mysql [for starters], i have been thinking of creating an ajax
tutorial [which happens to be my favorite subject on the web]. The problem with that is, to use ajax, u will need
to have mastered javascript as well as php/asp, and of course ur html and css should be at least average.
I don't quite know how to go about it, maybe i should just start from raw html and javascript tutorial first.
I am just starting an ajax script section on http://ds.mwebng.net/ [if u don't know what ajax is all about, don't bother visiting]
- i don't mean to sound rude, but u just wont get it.
******* Addition To This Post ****************
I have decided to carry beginners along, and have created a thread featuring how to learn dynamic web design on nl - it is on www.nl.mebng.net

(1) (2) (3) (4) (5) (6) (7) (8) (9) (10) ... (13) (Reply)

best BULK SMS provider in Nigeria ? / The Meaning Of CAPTCHA & 6 Types Of CAPTCHA / When You Are A Computer Guru And Your Girlfriend Needs Your Assistance

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 162
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.