What is PHP? A complete PHP guide

do you know What is PHP? if you don’t know don’t worry we will help you. in this PHP guide, We Will Discuss What is PHP? What is a PHP File? how to Comments in PHP? and much more. So Without Wasting Time Let’s Know About The LOOP.

you know PHP is a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft’s ASP. PHP is a server-side scripting language.

Before going through in detail about PHP, we must be aware with the following terms, given below:

What is PHP?

  • PHP stands for PHP: Hypertext Preprocessor.
  • PHP is a server-side scripting language, like ASP.
  • PHP scripts are executed on the server.
  • PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.).
  • PHP is open-source software.
  • PHP is free to download and use.

PHP is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly.

This is generally a good definition of PHP. However, it does contain a lot of terms you may not be used to. Another way to think of PHP is a powerful, behind the scenes scripting language that the visitors won’t see!

When someone visits the PHP webpage, the web server processes the PHP code. It then sees which parts it needs to show to visitors (content and pictures) and hides the other stuff (file operations, math calculations, etc.) then translates your PHP into HTML. After the translation into HTML, it sends the webpage to the visitor’s web browser.

It is also helpful to think of PHP in terms of what it can do for us. PHP will allow us to: 

(i) Reduce the time to create large websites.
(ii) Create a customized user experience for visitors based on information that you have gathered from them.
(iii) Open up thousands of possibilities for online tools. Check out PHP – HotScripts for examples of the great things that are possible with PHP.
(iv) Allow creation of shopping carts for e-commerce websites.

What is a PHP File?

  • PHP files can contain text, HTML tags, and scripts
  • PHP files are returned to the browser as plain HTML.
  • PHP files have a file extension of “.php”, “.php3”, or “.phtml”.

What is MySQL?

  • MySQL is a database server.
  • MySQL is ideal for both small and large applications.
  • MySQL supports standard SQL.
  • MySQL compiles on a number of platforms.
  • MySQL is free to download and use.

PHP + MySQL

  • PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix platform).

Why PHP?

  • PHP runs on different platforms (Windows, Linux, Unix, etc.).
  • PHP is compatible with almost all servers used today (Apache, IIS, etc.).
  • PHP is Free to download from the official PHP resource: www.php.net.
  • PHP is easy to learn and runs efficiently on the server-side.

Where to Start?

To get access to a web server with PHP support:

  • Install Apache (or IIS) on your own server, install PHP, and MySQL.
  • Or find a web hosting plan with PHP and MySQL support.

Basic PHP Syntax:

A PHP scripting block always starts with <?php and ends with?>. A PHP scripting block can be placed anywhere in the document. On servers with shorthand support enabled you can start a scripting block with <? and end with?>. For maximum compatibility, use the standard from (<?php) rather than the shorthand from.

<?php?>

A PHP file normally contains HTML tags, just like an HTML file, and some PHP scripting code. Below, we have an example of a simple PHP script which sends the text “Hello World” to the browser:

<html>
<body>
<?php
echo “Hello World”;
?>
</body>
</html>

Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguised one set of instructions from another. There are two basic statements to output text with PHP: echo and print. In the example above the echo statement is used to output the text “Hello World”.Note: The file must have a .php extension. If the file has .html extension, the PHP code will not be executed.

how to Comments in PHP?

In PHP, use // to make a single-line comment or /* and */ to make a large comment block. Using Comments in PHP Comments in PHP are similar to comments that are used in HTML. The PHP comment syntax always begins with a special character sequence and all text that appears between the start of the comment and the end will be ignored.

In HTML a comment’s main purpose is to serve as a note to the web developer or to others who may view the website’s source code. However, PHP’s comments are different in that they will not be displayed to your visitors. The only way to view PHP comments is to open the PHP file for editing. This makes PHP comments only useful to PHP programmers. In case one forgot what an HTML comment looked like, see our example given below.

HTML Code:

<!_ This is an HTML Comment _>

  1.  PHP Single Line Comment: While there is only one type of comment in HTML, PHP has two types. In the first type, the single line comment is discussed. The single line comment tells the interpreter to ignore everything that occurs on that line to the right of the comment. To do a single line comment type “//” or “#” and all text to the right will be ignored by the PHP interpreter.

PHP Code: 

<?php
echo “Hello World!”;// This will print out Hello World!
echo “<br/>Oopss… You can’t see my PHP comments!”; // echo “nothing”;
// echo “My name is Mani!”;
# echo “I don’t do anything either”;
?>

Output:

Hello World!
Oopss… You can’t see my PHP comments!

Notice that a couple of our echo statements were not evaluated because we commented them out with the single line comment. This type of line commenting is often used for quick notes about complex and confusing code or to temporarily remove a line of PHP code.

  1.  PHP Multiple Line Comment:
    Similar to the HTML comment, the multiline PHP comment can be used to comment out large blocks of code or write multiple line PHP comments. The multiple line PHP comment begins with “/* “and ends with “*/*.

Output:

Hello World!

One of the best commenting practices that can be recommended to new PHP programmers is… USE THEM!! So many people write complex PHP code and are either too lazy to write good comments or believe the commenting is not needed. Use single line comments for quick notes about a tricky part in the and use multiple line comments when one need to describe something in greater depth than a simple note.

<html>
<body>
<?php
//This is a comment/*
This is 
a comment
block
*/
?>
</body>
</html>

what is PHP Variables?

A variable is a means of storing a value, such as a text string “Hello World!” or the integer value 4. A variable can then be reused throughout the code, instead of having to type out the actual value over and over again. A variable is used to store information. They are used for storing values, like text strings, numbers or arrays. When a variable is declared, it can be used over again in your script. All variables in PHP start with a $ sign symbol. The correct way of declaring a variable in PHP:

$var_name= value;

New PHP programmers often forget the $ sign at the beginning of the variable. In the case, it will not work. Let’s try creating a variable containing a string, and a variable containing a number:

<?php
$txt=”Hello World!”;
$x=16;
?>

Note: Also, variable names are case-sensitive, so use the exact same capitalization when using a variable. The variable $a_number and $A_number are different variables in PHP’s eyes.


Some features of PHP variables:

  • In PHP, a variable does not need to be declared before adding a value to it.
  • In the example above, you see that you do not have to tell PHP which data type the variable is.
  • PHP automatically converts the variable to the correct data type, depending on its value.
  • In a strongly typed programming language, you have to declare (define) the type and name of the variable before using it.
  • In PHP, the variable is declared automatically when you use it.
  1.  PHP Variable Naming Conventions:
    Following few rules are essential to follow when choosing a name for the PHP variables.
  • PHP variables must start with a letter or underscore “_”.
  • PHP variables may only be composed of alphanumeric characters and underscores. a-z, A-Z, 0-9, or_.
  • Variables with more than one word should be separated with underscores. $my_variable.
  • Variables with more than one word can also be distinguished with capitalization. $myVariable.

PHP-Echo:

As explained in the previous article, the PHP command echo is a means of outputting text to the web browser. Use the echo command more than any other for a career in PHP. So let’s give it a solid perusal!

  1. Outputting a String:
    To output, a string, like the previous example, use PHP echo. One can place either a string variable or one can use quotes, as done below, to create a string that the echo function will output.

PHP Code:

<?php
$myString= “Hello!”;
echo $myString;
echo “<h5> I love using PHP!</h5>”;
?>

Output:

Hello!
I love using PHP!
In the above example, we output “Hello!” without a hitch. The text we are outputting is being sent to the user in the form of a web page, so it is important that we use proper HTML syntax!
In our second echo statement we use echo to write a valid Header 5 HTML statement. To do this, we simply put the <h5> at the beginning of the string and closed it at the end of the string. Just because you’re using PHP to make web pages does not mean you can forget about HTML syntax!

  1. Careful When Echoing Quotes!
    It is pretty cool that you can output HTML with PHP. However, careful when using HTML code or any other string that includes quotes! Echo uses quotes to define the beginning and end of the string, so use one of the following tactics if the string contains quotations:
  • Don’t use quotes inside your string.
  • Escape the quotes that are within the string with a backslash. To escape a quote just place a backslash directly before the quotation mark, i.e.\”
  • Use single quotes (apostrophes) for quotes inside your string.

Consider the following example: For the right and wrong use of echo:

PHP Code:

<?php
//This won’t work because of the quotes around specialH5!
echo “<h5 class=”specialH5”> I love using PHP!</H5>”;
//OK because we escaped the quotes!
echo “<h5 class=\”specialH5\”> I love using PHP!</h5>”;
// OK because we used an apostrophe ‘
echo “<h5 class=’ specialH5’> I love using PHP!</h5>”;
?>

For outputting a string that includes quotations, either use an apostrophe (‘) or escape the quotations by placing a backslash in front of it (\”). The backslash will tell PHP that the quotation to be used within the string and NOT to be used to end echo’s string.

(c) Echoing Variables:
Echoing variables is very easy. The PHP developers put in some extra work to make the common task of echoing all variables nearly foolproof! No quotations are required, even if the variable does not hold a string. Below is the correct format for echoing a variable.

PHP Code: 

<?php
$my_string= “Hello Mani. My name is:”;
$my_number= 4;
$my_letter= a;
echo $my_string;
echo $my_number;
echo $my_letter;
?>

Output:

Hello Mani. My name is: 4a
Echoing Variables and Text Strings
Variables can also be placed inside of double-quoted string (e.g. “string here and a $variable”). By putting a variable inside the quotes (“”), it is told to PHP to grab the string value of that variable and use it in the string. The example below shows an example of this cool feature.

PHP Code:

<?php
$my_string = “Hello Mani. My name is:”;
echo “$my_string Roop <br/>”;
echo “Hi, I’m Mani. Who are you? $my_string <br?>”;
echo “Hi, I’m Mani. Who are you? Hello Mani. My name is Roop

By placing variables inside a string one can save one self some time and make the code easier to read, though it does take some getting used to. Remember to use double-quotes, single-quotes will not grab the value of the value of the string. Single-quotes will just output the variable name to the string, like)$my_string),rather than (Hello Mani. My name is:).

(d) PHP Echo-Not a Function:
Echo is not a function, rather it is a language construct. When one uses functions in PHP, they have a very particular form, which we will be going over later. For now, just know that echo is a special tool that comes to know and love!

how to use PHP String Variables:

A string variable is used to store and manipulate text. String variables are used for values that contain characters. In this article, we are going to look at the most common functions and operators used to manipulate strings in PHP. After creating a string, try to manipulate it. A string can be used directly in a function or it can be stored in a variable. below , the PHP script assigns that text “Hello World” to a string variable called $txt:

<?php
$txt= “Hello World”;
Echo $txt;
?>

The output of the code above will be:

Hello World
Now, let’s try to use some different functions and operators to manipulate the string.

  1. The Concatenation Operator:
    There is only one string operator in PHP. The concatenation operator (.) is used to put two string values together. To concatenate two string variables together, use the concatenation operator:

<?php
$txt1=”Hello World!”;
$txt2=”What a nice day!”;
echo $txt1. “ “. $txt2;
?>

Output:

Hello World! What a nice day!

From the above code, it is obvious that concatenation operators are used two times. This is because of inserting a third string (a space character), to separate the two strings.

  1. The strlen( ) function:
    The strlen( ) function is used to return the length of a string. Let’s find the length of a string:

<?php
echo strlen(“Hello world!”);
?>

Output:

12

The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string).

(c) The strpos( ) function:
The strpos( ) function is used to search for a character/text within a string. If a match is found, it will return FALSE. Let’s see if we can find the string “world” in our string:

<?php
echo strpos(“Hello world!”,”world”);
?>

Output:

6

The position of the string “world” in the example above is 6. The reason is that, it is 6, is that the first character position in the string is 0, and not 1.

what is PHP-Operators?

In all programming languages, operators are used to manipulate or perform operations on variables and values. It is already seen the string consatenation operator “.” in the Echo Lesson and the assignment operator “=” in pretty much every PHP example so far. There are many operators used in PHP, so we have separated them into the following categories to make it easier to learn them all.

  1. Assignment Operators
  2. Arithmetic Operators
  3. Comparison Operators
  4. String Operators
  5. Combination Arithmetic & Assignment Operators

1. Assignment Operator:
Assignment operators are used to set a variable equal to a value or set a variable to another variable’s value. Such an assignment of value is done with the “=”, or equal character.

Example:

$my_var= 4;
$another_var= $my_var;

Now both $my_var and $another_var contain the value 4. Assignments can also be used in conjunction with arithmetic operators.

2. Arthmetic Operators:

OperatorEnglishExample
+Addition2+4
Subtraction6-2
*Multiplication5*3
/Division15/3
%Modulus43%10

PHP Code:

$addition= 2+4;
$subtraction= 6-2;
$multiplication= 5*3;
$division= 15/3;
$modulus= 5%2;
echo “Perform addition: 2+4= “.$addition.”<br/>”;
echo “Perform subtraction: 6-2= “.$subtraction.”<br/>”;
echo “Perform multiplication: 5*3= “.$multiplication.”<br/>”;
echo “Perform division: 15/3 = “.$division.”<br/>”;
echo “Perform modulus: 5%2= “.$modulus . “. Modulus is the remainder after the division operation has been performed. In this case it was 5/2, which has a remainder of 1.”;

Output:

Perform addition: 2+4=6
Perform subtraction: 6-2=4
Perform multiplication: 5*3= 15
Perform division: 15/3=5
Perform modulus: 5%2=1. Modulus is the remainder after the division operation has been performed. In this case it was 5/2, which has a reminder of 1.”,.

3. Comparison Operators:
Comparisons are used to check the relationship between variables and/or values. Comparison operators are used inside conditional statements and evaluate to either true or false. Here are the most important comparison operators of PHP.

Assume: $x= 4 and $y= 5;

OperatorEnglishExampleResult
==Equal To$x = = $yfalse
!=Not Equal To$x ! = $ytrue
<Less Than$x < $ytrue
>Greater Than$x > $yfalse
<=Less Than or Equal To $x < = $ytrue
>=Greater Than or Equal To$x > = $yfalse

4. String Operators:
It is already seen in the Echo topic, the period “.” is used to add two strings together, or more technically, the period is the concatenation operator for strings.

PHP Code:

$a_string= “Hello”;
$another_string= “Mani”;
$new_string= $a_string. $another_string;
echo $new_string. “!”;

Output:

Hello Mani!

5. Combination Arithmetic & Assignment Operators:
In programming it is a very common task to have to increment a variable by some fixed amount. The most common example of this is a counter. In order to increase a counter by 1, one would have:

$counter= $counter+1;
However, there is a shorthand for doing this.
$counter+=1;

This combination assignment/arithmetic operator would accomplish the same task. The downside to this combination operator is that it reduces code readability to those programmers who are not used to such an operator. Here are some examples of other common shorthand operators. In general, “+=” and “-=” are the most widely used combination operators.

OperatorEnglishExampleEquivalent 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”;
  1. Pre/Post-Increment & Pre/Post-Decrement:
    This may seem a bit absurd, but there is even shorter shorthand for the common task of adding 1 or subtracting 1 from a variable. To add one to a variable or “increment” use the “++” operator:

$x++; which is equivalent to $x += 1; or $x = $x + 1;
To subtract 1 from a variable, or “decrement” use the “_” operator:
$x_; which is equivalent to $x -= 1; or $x = $x – 1;

In addition to this “shorthand” technique, you can specify whether you want to increment before the line of code is being executed or after the line has executed. Our PHP code below will display the difference.

PHP Code:

$x = 4;
echo “The value of x with post-plusplus =” . $x++;
echo “<br/> The value of x after the post-plusplus is” . $x;
$x = 4;
echo “<br/> The value of x with pre-plusplus =”. ++$x;
echo “<br/> The value of x after the pre-plusplus is”. $x;

Output:

The value of x with post-plusplus = 4
The value of x after the post-plusplus is = 5
The value of x with with pre-plusplus = 5
The value of x after the pre-plusplus is = 5 

As you can see the value of $x++ is not reflected in the echoed text because the variable is not incremented until after the line of code is executed. However, with the pre-increment “++$x” the variable does reflect the addition immediately.

what is Conditional Statements:

Conditional statements are used to perform different actions based on different conditions. Very often to write code, perform different actions for different decisions. To do this, use conditional statements in code. In PHP, following conditional statements are essential:

  • if statement: Use this statement to execute some code only if a specified condition is true.
  • if…else statement: Use this statement to execute some code if a condition is true and another code if the condition is false.
  • if…elseif…else statement: Use this statement to select one of several blocks of code to be executed.
  • switch statement: Use this statement to select one of many blocks of code to be executed.
  1. The if Statement: Use the if statement to execute some code only if a specified condition is true.

Syntax: 

if (condition) code to be executed if condition is true;

The following example will output “Have a nice weekend!” if the current day is Friday:

<html>
<body>
<?php
$d=date(“D”);
if ($d== “Fri”) echo “Have a nice weekend!”;
?>
</body>
</html>

Notice that there is no ..else.. in this syntax. The code is executed Only if the specified condition is true.

  1. The if…else Statement: Use the if…else statement to execute some code if a condition is true and another code if a condition is false.

Syntax:

if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

Example: The following example will output “Have a nice weekend!” if the current day is Friday, otherwise it will output “Have a nice day!”:

<html>
<body>
<?php
$d=date(“D”);
if ($d== “Fri”)
echo “Have a nice weekend!”;
Else
echo “Have a nice day!”;
?>
</body>
</html>

If more than one line should be executed if a condition is true/false, the lines should be enclosed within curly braces:

<html>
<body>
<?php
$d=date(“D”);
if ($d== “Fri”)
{
echo “Hello!<br/>”;
echo “Have a nice weekend!”;
echo “See you on Monday!”;
}
?>
</body>
</html>

  1. The if…elseif…else Statement: Use the if…elseif…else statement to select one of several blocks of code to be executed.

Syntax:

if (condition)
code to be executed if condition is true;
elseif (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

Example: The following example will output “Have a nice weekend!” if the current day is friday, and “Have a nice Sunday!” if the current day is Sunday. Otherwise it will output “Have a nice day!”:

<html>
<body>
<?php
$d=date(“D”);
if ($d== “Fri”)
echo “Have a nice day!”;
elseif ($d==”Sun”)
echo “Have a nice Sunday!”;
else
echo “Have a nice day!”;
?>
</body>
</html>

  1. PHP Switch Statement: Use the switch statement to select one of many blocks of code to be executed.

In the previous topics, we covered the various elements that make up an If Statement in PHP. However, there are times when if statement is not the most efficient way to check for certain conditions.

For example, we might have a variable that stores travel destinations and you want to pack according to this destination variable. In this example you might have 20 different locations that you would have to check with a nasty long block of If/ElseIf/ElseIf/…statements. This doesn’t sound like much fun to code, let’s see if we can do something different. With the use of the switch statement you can check for all these conditions at once, and the great thing is that it is actually more efficient programming to do this. A true win-win situation!

The way the Switch statement works is it takes a single variable as input and then checks it against all the different cases you set up for that switch statement. Instead of having to check that variable one at a time, as it goes through a bunch of If Statements, the Switch statement only has to check one time.

Syntax:

switch (n)
{
case label1:
code to be executed if n= label1;
break;
case label2:
code to be executed if n= label2;
break;
default:
code to be executed if n is different from both label1 and label2;
}

This is how it works:
First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case autoatically. The default statement is used if no match is found.

Example:

<html>
<body>
<?php
switch ($x)
{
case 1:
echo “Number 1”;
break;
case 2:
echo “Number 2”;
break;
case 3:
echo “Number 3”;
break;
default:
echo “No number between 1 and 3”;
}
?>
</body>
</html>

what is a PHP Array?

An array is a data structure that stores one or more values in a single value. For experienced programmers, it is important to note that PHP’s array are actually maps (each key is mapped to a value). An array stores multiple values in one single variable. A variable is a storage area holding a number or text. The problem is, a variable will hold only one value. An array is a special variable, which can store multiple values in one single variable. If one have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

$car1 = “Saab”;
$cars2 = “Volvo”;
$cars3 = “BMW”;

However, what if one want to loop through the cars and find a specific one? And what if one had not 3 cars, but 300?
The best solution here is to use an array! An array can hold all your variable values under a single name. And you can access the values by referring to the array name. Each element in the array has its own index so that it can be easily accessed. In PHP, there are three kind of arrays:

  • Numeric array: An array with numeric index.
  • Associative array: An array where each ID key is associated with a value.
  • Multidimensional array: An array containing one or more arrays.
  1. Numeric array: A numeric array stores each array element with a numeric index. There are two methods to create a numeric array.
  1.  In the following example, the index are automatically assigned (the index starts at 0): $cars= array(“Saab”, “Volvo”, “BMW”, “Toyota”);
  2.  In the following example, assign the index manually:

$cars[0]= “Saab”;
$cars[1]= “Volvo”;
$cars[2]= “BMW”;
$cars[3]= “Toyota”;

Example: In the following example, access the variable values by referring to the array name and index:

<?php
$cars[0]= “Saab”;
$cars[1]= “Volvo”;
$cars[2]= “BMW”;
$cars[3]= “Toyota”;
echo $cars[0]. “and”. $cars[1]. “are Swedish cars.”;
?>

Output: 

Saab and Volvo are Swedish cars.

2. Associative Arrays:
An associative array, each ID key is associated with a value. When storing data about specific named values, a numerical array is not always the best way to do it. With associative arrays can use the values as keys and assign values to them.

Example 1: An array to assign ages to the different persons:

$ages = array(“Mani”= 24, “Manish”= 23, “Ekam”=>25);

Example 2: This example is the same as example 1, but shows a different way of creating the array:
$ages[‘Mani’] = “24”;
$ages[‘Manish’] = “23”;
$ages[‘Ekam’] = “25”;

The ID keys can be used in a script:
<?php
$ages[‘Mani’] = “24”;
$ages[‘Manish’] = “23”;
$ages[‘Ekam’] = “25”;
echo “Mani is “. $ages[‘Mani’]. “years old.”;
?>

Output:

Mani is 24 years old.

3. Multidimensional Arrays:
In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on.

Example: In this example we create a multidimensional array, with automatically assigned ID keys:

$families = array
(
“Griffin”=>array
(
“Peter”
“Lois”,
“Megan”
),
“Quagmire”=>array
(
“Glenn”
),
“Brown”=>array
(
“Cleveland”,
“Loretta”,
“Junior”
)
);

The array above would look like this if written to the output:
Array
(
[Griffin] => Array
(
[0] => Peter
[1] => Lois
[2] => Megan
)
[Quagmire] => Array
(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
)

Example 2: Let’s try displaying a single value from the array above:

echo “Is” . $families[‘Griffin’][2].
“a part of the Griffin family?”;
The code above will output:
Is Megan a part of the Griffin family?

what is PHP Loops? and types of loops

Repetitive tasks are always a burden to us. Deleting spam email, sealing 50 envelops, and going to work are all examples of tasks that are repeated. The nice thing about programming is that one can avoid such repetitive tasks with a little bit of extra thinking. Most often these repetitive tasks are conquered in the loop. The idea of a loop is to do something over and over again until the task has been completed.

“Loops execute a block of code a specified number of times, or while a specified condition is true.”

Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this. In PHP, we have the following looping statements:

  • While: loops through a block of code while a specified condition is true.
  • do…while: Loops through a block of code once, and then repeats the loop as long as a specified condition is true.
  • for: Loops through a block of code a specified number of times.
  • foreach: Loops through a block of code for each element in an array.
  1. The while Loop: The while loop executes a block of code while a condition is true.

Syntax:

while (condition)
{
code to be executed;
}

Example: The example below defines a loop that starts with i = 1. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:

<html>
<body>
<?php
$i=1;
while($i<=5)
{
echo “The number is”. $i. “<br/>;
$i++;
}
?>
</body>
</html>

Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

  1. The do…while Statement:
    The do…while statement will always execute the block of code once, it will then check the condition, and repeat the loop while the condition is true.

Syntax: 
do
{
code to be executed;
}
while(condition);

Example: The example below defines a loop that starts with i = 1. It will the increment i with 1, and write some output. Then the condition is checked, and the loop will continue to run as long as i is less than, or equal to 5:
<html>
<body>
<?php
$i=1;
do
{
$i++;
echo “The number is”. $i. “<br?>”;
}
while ($i<=5);
?>
</body>
</html>

Output:
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6

  1. The for Loop:
    The for loop is used when you know in advance how many times the script should run. The for loop is simply a while loop with a bit more code addes to it. The common tasks that are covered by a for loop are:
  • Set a counter variable to some initial value.
  • Check to see if the conditional statement is true.
  • Execute the code within the loop.
  • Increment a counter at the end of each iteration through the loop.

The for loop always allows to define these steps in one easy line of code. It may seem to have a strange from, so pay close attention to the syntax used!
Syntax:
for (init; condition; increment)
{
code to be executed;
}

Paramenters: 

  • init: Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop).
  • condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
  • increment: Mostly used to increment a counter (but can be any code to be executed at the end of the loop).

Note: Each of the parameters above can be empty, or have multiple expressions (separated by commas).

Example: The example below defines a loop that starts with i = 1. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:
<html>
<body>
<?php
for ($i=1; $i<=5; $i++)
{
echo “The number is”. $i. “</br>”;
}
?>
</body>
</html>

Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

  1. The foreach Loop:
    The foreach loop is used to loop through arrays. Imagine an associative array that one want to iterate through. PHP provides an easy way to use every element of an array with the Foreach statement. In plain English this statement will do the following: For each item in the specified array execute this code. While a For Loop and while Loop will continue until some condition fails, the For Each loop will continue until it has gone through every item in the array.

Syntax: 

foreach ($array as $value)
{
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value (and the array pointer is moved by one) – so on the next loop iteration, you’ll be looking at the next array value.

Example: The following example demonstrates a loop that will print the values of the given array:
<html>
<body>
<?php
$x=array(“one”, “two”, “three”);
foreach ($x as $value)
{
echo $value. “<br/>”;
}
?>
</body>
</html>

Output:
one 
two
three

what is PHP Functions? and how to create PHP Function

A function is just a name we give to a block of code that can be executed whenever we need it. This might not seem like that big of an idea, but believe me, when you understand and use functions you will be able to save a ton of time and write code that is much more readable! For example, you might have a company motto that you have to display at least once on every webpage. If you don’t, then you get fired! Well, being the savvy PHP programmer you are, you think to yourself, “This sounds like a situation where I might need functions.”

Tip: Although functions are often thought of as an advanced topic for beginning programmer to learn, if you take it slow and stick with it, functions can be just minor speedbump in your programming career. So don’t give up if you functions confuse you at first!

Creating Your First PHP Function:
While creating a function, first name it, like my CompanyMotto. It is with this function name that one will be able to call upon your function, so make it easy to type and understand.

The actual syntax for creating a function is pretty self-explanatory, but one can be the judge of that. First, tell PHP that one want to create a function. Do this by typing the keyword function followed by function followed by function name and some other stuff (Which we’ll talk about later). This is how one would make a function called my CompanyMotto.

Note: We still have to fill in the code for myCompanyMotto.

PHP Code:

<?php
function myCompanyMotto(){
}
?>

Note: Function name can start with a leteer or underscore “_”, but not a number!

With a properly formatted function in place, we can now fill in the code that we want our function to execute. Do you see the curly braces in the above example “{ }”? These braces define where our function’s code goes. The opening curly brace “{“ tells php that the function’s code is starting and a closing curly brace “}” tells PHP that our function is done!

We want our function to print out the company motto each time it’s called, so that sounds like it’s a job for the echo command!

PHP Code: 

<?php
function myCompanyMotto(){
echo “We deliver quantity, not quality!<br/>”;
}
?>

It is first PHP function from scratch! Notice that the code that appears within a function is just the same as any other PHP code.

Using PHP Function: Note that after completion of coding the PHP function, it is time to put it through a test run. Below is a simple PHP script. Let’s do two things: add the function code to it and use the function twice.

PHP Code: 

<?php
echo “Welcome to dreamhigh.com<br/>”;
echo “Well, thanks for stopping by!<br?>”;
echo “and remember… <br/>”;
?>

PHP Code with Function:

<?php
function myCompanyMotto(){
echo “We deliver quantity, not quality!<br/>”;
}
echo “Welcome to dreamhigh.com<br/>”;
myCompanyMotto();
echo “Well,thanks for stopping by!<br/>”;
echo “and remembe…<br/>”;
myCompanyMotto();
?>

Output:
Welcome to dreamhigh.com
We deliver quantity, not quality!
Well, thanks for stopping by!
and remember…
We deliver quantity, not quality!

Although this was a simply example, it is important to understand that there is a lot going on and there are a lot of areas to make errors. While creating a function, follow these simple guidelines:

  • Always start your function with the keyword function.
  • Remember that your function’s code must be between the “{“ and the “}”.
  • When you are using your function, be sure you spell the function name correctly.

PHP Function Parameters:
Another useful thing about functions is that one can send them information that the function myCompanyMotto isn’t all that useful because all it does, and ever will do, is print out a single, unchanging string.

However, if we were to use parameters, then we would be able to add some extra functionality! A parameter appears with the parentheses “( )” and looks just like a normal PHP variable. Let’s create a new function that creates a custom greeting based off of a person’s name.

Our parameter will be the person’s name and our function will concatenate this name into a greeting string. Here’s what the code would look like.

PHP Code with Function:

<?php
function myGreeting($firstName){
echo “Hello there”. $firstName. “!<br?>”;
}
?>

When we use our myGreeting function we have to send it a string containing someone’s name, otherwise it will break. When one add parameters, one also add more responsibility, the programmer! Let’s call our new function a few times with some common first names.

PHP Code:

<?php
function myGreeting($firstName){
echo “Hello there”. $firstName. “!<br/>”;
}
myGreeting(“Mani”);
myGreeting(“Manish”);
myGreeting(“Ekam”);
myGreeting(“Roop”);
?>

Display:
Hello there Mani!
Hello there Manish!
Hello there Ekam!
Hello there Roop!

It is also possible to have multiple parameters in a function. To separate multiple parameters PHP uses a comma “,”. Let’s modify our function to also include last names.

PHP Code:

</php
function myGreeting($firstName, $lastName){
echo “Hello there “.$firstName.” “.$lastName.”!<br/>”;
}
myGreeting(“Mani”, “Dhiman”);
myGreeting(“Manish”, “Mishra”);
myGreeting(“Ekam”, “Suray”);
myGreeting(“Roop”, “Mishra”);
?>

Display:
Hello there Mani Dhiman!
Hello there Manish Mishra!
Hello there Ekam Suray!
Hello there Roop Mishra!

PHP Functions Returning Values:
Besides being able to pass functions information, one can also have them return a value. however , a function can only return one thing, although that thing can be any integer, float, array, string, one. that you choose!

How does it return a value though? Well, when the function is used and funishes executing, it sort of changes from being a function name into being a value. To capture this one you can set a variable equal to the function. Something like:

$myVar= somefunction( );

Let’s demonstrate this returing of a value by using a simply function that returns the sum of two integers.

PHP Code:

<?php
function mySum($numX, $numY){
$total= $numX+$numY;
return $total;
}
$myNumber=0;
echo “Before the function, myNumber= “.$myNumber.”<br/>”;
$myNumber= mySum(3,4);//Store the result of mySum in $myNumber
echo “After the function, myNumber= “.myNumber.”<br/>”;
?>

Output:
Before the function, myNumber=0
After the function, myNumber=7

When we first print out the value of $myNumber it is still set to the original value of 0. However, when we set $myNumber equal to the function mySum, $myNumber is set equal to mySum’s result. In this case, the result was 3+4=7, which was successfully stored into $myNumber and displayed in the second echo statement!

Using PHP with HTML Forms:

A very common application of PHP is to have HTML form gather informtion from a website’s visitor and then use PHP to do process that information. In this chapter, we will simulate a small business’s website that is implementing a very simple order form. The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input.

  1. PHP Form Handling:
    The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML pages will automatically be available to the PHP scripts.

Example: The example below contains an HTML form with two input fields and a submit button:
<html>
<body>
<form action=welcome.php” method= “post”>
Name: <input type= “text” name= “fname”/>
Age: <input type= “text” name= “age”/>
<input type= “Submit”/>
</form>
</body>
</html>

When a user fills out the form above and click on the submit button, the form data is sent to a PHP file, called “welcome.php”:

“Welcome.php” looks like this:
<html>
<body>
Welcome <?php echo $_POST[“fname”];?>!<br/>
You are <?php echo $_POST[“age”];?> years old.
</body>
</html>

Output:
Welcome John!
You are 28 years old.

  1. Form Validation:
    User input should be validation on the browser whenever possible(by client scripts). Browser validation is faster and reduces the server load. One should consider server validation if the user input will be inserted into a database. A good way to validate form on the server is to post the form to itself, instead of jumping to a different page. The user will then get the error messages on the same page as the form. This makes it easier to discover the error.
  2. The $_GET Variable:
    The predefined $_GET variable is used to collect values in a form with method=”get” Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser’s address bar) and has limits on the amount of information to send.

Example: 
<form action= “welcome.php” method= “get”>
Name: <input type= “text” name= “fname”/>
Age: <input type= “text” name= “age”/>
<input type= “submit”/>
</form>

Note: This method should not be used when sending passwords or other sensitive information!

However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.

Note: The get method is not suitable for very large variable values. It should not be used with values exceeding 2000 characters.

  1. PHP $_POST Function:
    In PHP, the predefined $_POST variable is used to collect values in a form with method= “post”. The predefined $_POST variable is used to collect values from a form sent with method= “post”. Information sent from with the POST method is invisible to others and has no limits on the amount of information to send.

Note: However, there is an 8 Mb max size for the POST method, by default (can be changed by setting the post_max_size in the php.ini file).

Example: 
<form action= “welcome.php” method= “post”>
Name: <input type= “text” name= “fname”/>
Age: <input type= “text” name= “age”/>
<input type= “submit”/>
</form>

Information sent from a form with the POST method is imvisible to others and has no limits on the amount of information to send. However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

  1. The PHP $_REQUEST Variable:
     The predefined $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. The $_REQUEST variable can be used to collect form data sent with both the GET and POST methods.

Example: 

Welcome <?php echo $_REQUEST[“fname”];?>!<br/>

You are <?php echo $_REQUEST[“age”];?>years old.

PHP Server Side Includes(SSI):

One can insert the content of one PHP file into another PHP file before the server executes it, with the include( ) or require( ) function. The two functions are identical in every way, except how they handle error:

  • include( ) generates a warning, but the script will continue execution.
  • require( ) generates a fatal error, and the script will stop.

These two functions are used to create functions, headers, footers, or elements that will be reused on multiple pages. Server side includes saves a lot of work. This means that one can create a standard header, footer, or menu file for all the web pages. When the header needs to be updated, one can only update the include file, or when one add a new page to the site, one can simply change the menu file (instead of updating the links on all the web pages).

  1. PHP include( ) Function:  
    The include( ) function takes all the content in a specified file and includes it in the current file. If an error occurs, the include( ) function generates a waring, but the script will continue execution.

Example 1:  Assume a standard header file, called “header.php”. To include the hedaer file in a page, use the include( ) function:
<html>
<body>
<?php include(“header.php”);?>
<h1> Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>

Example 2: Assume a standard menu file, called “menu.php”, that should be used on all pages:
<a href= “/default.php”>Home</a>
<a href= “/tutorials.php”>Tutorials</a>
<a href= “/references.php”>References</a>
<a href= “/examples.php”>Examples</a>
<a href= “/about.php”>About Us</a>
<a href= “/contact.php”>Contact Us</a>

All pages in the Web site should include this menu file. Here is how it can be done:

<html>
<body>
<div class= “leftmenu”>
<?php include(“menu.php”);?>
</div>
<h1>Welcome to my home page.</h1>
<p>Some text.</p>
</body>
</html>

If one look at the source code of the page above (in a browser), it will look like this:

<html>
<body>
<div class= “leftmenu”>
<a href= “/default.php”>Home</a>
<a href= “/tutorials.php”>Tutorials</a>
<a href= “/references.php”>References</a>
<a href= “/examples.php”>Examples</a>
<a href= “/about.php”>About Us</a>
<a href= “/contact.php”>Contact Us</a>
</div>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>

  1. PHP require( )Function:
    The require( ) function is identical to include(), except that it handles errors differently. If an error occurs, the include( ) function generates a warning, but the script will continue execution. The require( ) generates a fatal error, and the script will stop.

Error Example include( ) Function: 
<html>
<body>
<?php
include(“wrongFile.php”);

Warning: include( ) [function.include]:
Failed opening ‘wrongFile.php’ for inclusion
(include_path=’ .;C:\php5\pear’)
in C:\home\website\test.php on line 5

Hello World!

Notice that the echo statement is executed! This is because a warning does not stop the script execution.

Error Example require( ) Function

Now, let’s run the same example with the require( ) function.
<html>
<body>
<?php
require(“wrongFile.php”);
echo “Hello World!”;
?>
</body>
</html>
Error message:

Warning: require(WrongFile.php) [function.require]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5

Fatal error: require( ) [function.require]:

Failed opening required ‘wrongFile.php’
(include_path=’.;C:\php5\pear’)
in C:\home\website\test.php on line 5

The echo statement is not executed, because the script execution stopped after the fatal error. It is recommended to use the require( ) function instead of include( ), because scripts should not continue after an error.

what is PHP File Handling?

There are various functions used for file handling in PH1) Opening a File: The fopen( ) function is used to open files in PHP. The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened:
<html>
<body>
<?php
$file= fopen(“welcome.txt”, “r”);
?>
</body>
</html>

The file may be opened in one of the following modes:

ModesDescription
rRead only. Starts at the beginning of the file.
r+Read/Write. Starts at the beginning of the file.
wWrite only. Opens and clears the contents of the file; or creates a new file if it doesn’t exist.
w+Read/Write.Opens and clears the contents of the file; or creates a new file if it doesn’t exist.
aAppend. Opens and writes to the end of the file or creates a new file if it doesn’t exist.
a+Read/Append. Preserves file content by writing to the end of the file.
xWrite only. Creates a new file. Returns FALSE and an error if file already exists.
x+Read/Write. Creates a new file, Returns FALSE and an error if file already exists.

Note: If the fopen( ) function is unable to open the specified file, it returns 0 (false).

Example:  The following example generates a message if the fopen( ) function is unable an open the specified file:
<html>
<body>
<?php
$file= fopen(“welcome.txt”, “r”) or exit(“Unable to open file!”);
?>
</body>
</html>

2. Closing a File:
The fclose( ) function is used to close an open file:
<?php
$file= fopen(“text.txt”, “r”);
//some code to be executed
fclose($file)
?>

  1. Check End-of-file:
    The feof( ) function checks if the “end-of-file” (EOF) has been reached. The feof( ) function is useful for looping through data of unknown length. You cannot read from files opened in w, a, and x mode!

if (feof($file)) echo “End of file”;

  1. Reading a file Line by Line:
    The fgets( ) function is used to read a single line from a file. After a call to this function the file pointer has moved to the next line.

Example: The example below reads a file line by line, until the end of file is reached:
<?php
$file= fopen(“welcome.txt”, “r”) or exit(“Unable to open file!”);
//Output a line of the end is reached 
while(!feof($file))
{
echo fgets($file). “<br/>”;
}
fclose($file);
?>

  1. Reading a File Character by Character:
    The fgetc( ) function is used to read a single character from a file. After a call to this function the file pointer moves to the next character. 

Example: The example below reads a file character by character, until the end of file is reached:
<?php
$file=fopen(“welcome.txt”, “r”) or exit(“Unable to open file!”);
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>

PHP File Upload: 

With PHP, it is possible to upload files to the server.

  1. Create an Upload-File Form:
    To allow users to upload files from a form can be very useful. Look at the following HTML form for uploading files:

<html>
<body>
<form action= “upload_file.php” method= “post”
enctype= “multipart/form-data”>
<label for= “file”> Filename:</label>
<input type= “file” name= “file” id= “file”/>
<br/>
<input type= “submit” name= “submit” value= “Submit”/>
</form>
</body>
</html>

Notice the following about the HTML form above:

  • The enctype attribute of the <form> tag specifies which content-type to use when submitting the form. “multipart/form-data” is used when a form requires binary data, like the contents of a file, to be uploaded/.
  • The type= “file” attribute of the <input> tag specifies that the input should be processed as a file. For example, when viewed in a browser, there will be a browser-button next to the input field.

Note: Allowing users to upload files is a big security risk. Only permit trusted users to perform file uploads.

  1. Create The Upload Scripts:
    The “upload_file.php” file contains the code for uploading a file:

<?php
if ($_FILes[“file”][“error”]>0)
{
echo “Error:” . $_FILES[“file”][“error”]. “</br>”;
}
else
{
echo “Upload:” .$_FILES[“file”][“name”]. “<br/>”;
echo “Type:” .$_FILES[“file”][“type”]. “<br/>”;
echo “Size:” .$_FILES[“file”][“size”]/ 1024). “Kb<
br/>”;
echo “Stored in:” .$_FILES[“file”][“tmp_name”];}
?>

By using the global PHP $_FILES array you can upload files from a client computer to the remote server.

The first parameter is the form’s input name and the second index can be either “name”, “type”, “size”, “tmp_name” or “error”. Like this:

  • $_FILES[“file”][“name”]- the name of the uploaded file.
  • $_FILES[“file”][“type”]- the type of the uploaded file.
  • $_FILES[“file”][“size”]- the size of the uploaded file.
  • $_FILES[“file”][“tmp_name”]- the name of the temporary copy of the file stored on the server.
  • $_FILES[“file”][“error”]- the error code resulting from the file upload.

This is a very simple way of uploading files. For security reasons, you should add restrictions on what the user is allowed to upload.

  1. Restrictions on Upload:
    In this script we add some restrictions to the file upload. This user may only upload .gif or .jpeg files and the file size must be under 20 kb:

<?php
if ((($_FILES[“file”][“type”]== “image/gif”)
|| ($_FILES[“file”][“type”]== “image/jpeg”)
|| ($_FILES[“file”][“type”]== “image/pjeg”))
&& ($_FILES[“file”][“size”]< 20000))
{
if ($_FILES[“file”][“error”]> 0)
{
echo “Error:” . $_FILES[“file”][“error”]. “<br/>”;
}
else
{
echo “Upload:” . $_FILES[“file”][“name”]. “<br/>”;
echo “Type:” . $_FILES[“file”][“type]. “<br/>”;
echo “Size:” . ($_FILES[“file”][“size”]/ 1024). “Kb<br/>”;
echo “Stored in:” . $_FILES[“file”][“tmp_name”];
}
}
else
{
echo “Invalid file”;
}
?>

Note: For IE to recognize jpg files the type must be pjeg, for FireFox it must be jpeg.

  1. Saving the Uploaded File:
    The examples above create a temporary copy of the uploaded files in the PHP temp folder on the server. The temporary copied files disappear when the script ends. To store the uploaded file we need to copy it to a different location:

<?php
if ((($_FILES[“file”][“type”]== “image/gif”)
|| ($_FILES[“file”][“type”]== “image/jpeg”)
|| ($_FILES[“file”][“type”]== “image/pjeg”))
&& ($_FILES[“file”][“size”]< 20000))
{
if ($_FILES[“file”][“error”]> 0)
{
echo “Return Code:” . $_FILES[“file”][“error”]. “<br/>”;
}
else
{
echo “Upload:” .$_FILES[“file”][“name”]. “<br/>”;
echo “Type:” .$_FILES[“file”][“type”]. “<br/>”;
echo “Size:” .($_FILES[“file”][“size”]/ 1024). “Kb<br/>”;
echo “Temp file:” .$_FILES[“file”][“tmp_name”]. “<br/>”;
if (file_exists(“upload/”. $_FILES[“file”][“name”]))
{
echo $_FILES[“file”][“name”]. “Already exists.”;
}
else
{
move_uploaded_file($_FILES[“file”][“tmp_name”],
“upload/” .$_FILES[“file”][“name”]);
echo “Stored in:” . “upload/” .$_FILES[“file”][“name”];
}
}
}
else
{
echo “Invalid file”;
}
?>

The script above checks if the file already exists, if it does not, it copies the file to the specified folder. This example saves the file to a new folder called “upload”.

what are PHP Sessions? 

A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application. When we are working with an application, we open it, do some changes and then we close it. This is much like a Session. The computer knows who we are. It knows when you start the application and when we end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn’t maintain state.

A PHP session solves this problem by storing user information on the server for later use (i.e. username, shopping items, etc.). However, session information is temporary and will be deleted after the user has left the website. If a permanent storage is needed, store the data in a database.

Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.

  1. Starting a PHP Session:
    Before storing user information in the PHP session, one must first start up the session. The session_start( ) function must appear BEFORE the <html>tag:

<?php session_start( ):?>
<html>
<body>
</body>
</html>

The code above will register the user’s session with the server, allowing it to start saving user information, and assign a UID for that user’s session.

  1. Storing a Session Variable:
    The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:

<?php
session_start( );
//store session data
$_SESSION[‘views’]=1;
?>
<html>
<body>
<?php
//retrieve session data
echo “Pageviews=”. $_SESSION[‘view’];
?>
</body>
</html>

Output:
Pageviews=1 

In the example below, we create a simple page-views counter. The isset() function checks if the “views” variable has already been set. If “views” has been set, we can increment our counter. If “views” doesn’t exist, we create a “views” variable, and set it to 1:
<?php
session_start( );
if(isset($_SESSION[‘views’]))
$_SESSION[‘views’]=$_SESSION[‘views’]+1;
else
$_SESSION[‘views’]=1;
echo “Views”=”. $_SESSION[‘views’];
?>

  1. Destroying a Session:
    In order to delete some session data, use the unset( ) or the session_destroy( ) function. The unset( ) function is used to free the specified session variable: 

<?php
unset($_SESSION[‘views’]);
?>
Session can also be completely destroyed by calling the session_destroy() function:
<?php
session_destroy( );
?>

Note:  session_destroy( ) will reset your session and you will lose all your stored session data.

PHP Sending E-mails: 

PHP allows you to send e-mails directly from a script. The PHP mail( ) function is used to send emails from inside a script.

Syntax:

mail(to, subject, message, header, parameters)

ParametersDescription
ToRequired. Specifies the receiver / receivers of the email
subjectRequired. Specifies the subject of the email.Note: This parameter can’t contain any newline characters
messageRequired. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters
headersOptional. Specifies additional headers, like from, Cc, and Bcc. the additional headers should be separated with a CRLF (\r\n)
parametersOptional. Specifies an additional parameter to the sendmail program

Note: For the mail functions to be available, PHP requires an installed and working email system. The program to be used is defined by the configuration settings in the php.ini file.

  1. PHP Simple E-Mail:
    The simplest way to send an email with PHP is to use a text email. In the example below we first declare the variables ($to, $subject, $message, $from, $headers), then we use the variables in the mail( ) function to send an e-mail:

<?php
$to= “someone@example.com”;
$subject= “Test mail”;
$message= “Hello! This is a simple email message.”;
$from= “someonelse@example.com”;
$header= “From:”. $from;
mail($to,$subject,$message,$header);
echo “Mail Sent.”;
?>

  1. PHP Mail From:
    With PHP, one can create a feedback-from on his website. The example below sends a text message to a specified e-mail address:

<html>
<body>
<?php
if (isset($_REQUEST[‘email’]))
//if “email” is filled out, send email
{
//send email
$email= $_REQUEST[‘emails’];
$subject= $_REQUEST[‘subject’];
$message= $_REQUEST[‘message’];
mail(“someone@example.com”, “$subject”,
$message, “Form:” $email);
echo “Thank you for using our mail form”;}
else
//if “email” is not filled out, display the form
{
echo “<form method= ‘post’ action= ‘mailform.php’>
Email: <input name= ‘email’ type= ‘text’/><br/>
Message: <br/>
<textarea name= ‘message’ rows= ‘15’ cols= ‘40’>
</textarea><br/>
<input type=submit’/>
</form>”;
}
?>
</body>
</html>

This is how the example above works:

  • First, check if the email input field is filled out.
  • If it is not set (like when the page is first visited); output the HTML form.
  • If it is set (after the form is filled out); send the email from the form.
  • When submit is pressed after the form is filled out, the page reloads, sees that the email input is set, and sends the email.

Note: This is the simplest way to send e-mail, but it is not secure.

PHP MySQL Introduction:

MySQL is the most popular open-source database system. MySQL is a database. The data in MySQL is stored in database objects called tables. A table is a collection of related data entries and it consists of columns and rows. Databases are useful when storing information categorically. A company may have a database with the following tables: “Employees”, “Products”, “Customers” and “Orders”.

  1. Database Tables:
    A database most often contains one or more tables. Each table is identified by a name (e.g. “Customers” or “Orders”). Tables contain records (rows) with data. Below is an example of a table called “Persons”:
Last NameFirst NameAddressCity
HansenOlaTimoteivn 10Sandnes
SvendsonToveBorgvn 23Sandnes
PettersenKariStorgt 20Stavanger

The table above contains three records (one for each person) and four columns (LastName, FirstName, Address, and City).

  1. Queries:
    A query is a question or a request. With MySQL, we can query a database for specific information and have a recordset returned. Look at the following query:

SELECT LastName FROM Person

The query above selects all the data in the “LastName” column from the “Persons” table, and will return a recordset like this:

Last Name
Hansen
Svendson
Pettersen
  1. Connect to a Database:
    The free MySQL database is very often used with PHP. Before you can access data in a database, create a connection to the database. In PHP, this is done with the mysql_connect( ) function.

Syntax: 
mysql_connect(servername,username,password);

ParameterDescription
severnameOptional. Specifies the server to connect to. Default value is localhost:3306”
usernameOptional. Specifies the username to log in with. Default value is the name of the user that owns the server process.
passwordOptional. Specifies the password to log in with. Default is “”

Note: There are more available parameters, but the ones listed above are the most important.

Example: In the following example, we store the connection in a variable ($con) for later use in the script. The “die” part will be executed if the connection fails:
<?php
$con= mysql-connect(“localhost”, “peter”, “abc123”);
if (!$con)
{
die(‘Could not connect:’. mysql_error());
}
//some code
?>

4. Closing a Connection:
The connection will be closed automatically when the script ends. To close the connection before, use the mysql_close() function:
<?php
$con= mysql_connect(“localhost”, “peter”, “abc123”);
if (!$con)
{
die(‘Could not connect:’.mysql_error());
}
//some code
mysql_close($con);
?>

5. Create Database and Tables:
A database holds one or multiple tables. The CREATE DATABASE statement is used to create a database in MySQL.

Syntax:
CREATE DATABASE database_name

To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection.

Example: The following example creates a database called “my_db”:
<?php
$con= mysql_connect(“localhost”, “peter”, “abc123”);
if (!$con)
{
die(‘Could not connect:’. mysql_error( ));
}
if (mysql_query(“CREATE DATABASE my_db”,$con))
{
echo “Database created”;
}
else
{
echo “Error creating database:”. mysql_error();
}
mysql_close($con);
?>

6. Create a Table:
The CREATE TABLES statement is used to create a table in MySQL.

Syntax:
CREATE TABLE table_name
(
Column_name1 data_type,
Column_name2 data_type,
Column_name3 data_type,

)

We must add the CREATE TABLE statement to the mysql_query( ) function to execute the command.

Example: The following example creates a table named “Persons”, with three columns. The column names will be “FirstName”, “LastName” and “Age”:

<?ph
$con =  mysql_connect(“localhost”,’”peter”,”abc123”);$con =
mysql_connect(“localhost”,”peter”,”abc123”);
if (!$con)
{
die(‘Could not connect:’. mysql_error());
}
mysql_select_db(“my_db”,$con);
mysql_query(“INSERT INTO Persons (FirstName, LastName, Age)
VALUES (‘Peter’, ‘Griffin’, ‘35’)”);
mysql_query(“INSERT INTO Persons (FirstName, LastName, Age)
VALUES (‘Glenn’, ‘Quagmire’, ‘33’)”);
mysql_close($con);
?>

9. Insert Data From a Form Into a Database:
Now we will create an HTML form that can be used to add new records to the “Persons” table.

Here is the HTML form:
<html>
<body>
<form action= “insert.php” method= “post”>
Firstname: <input type= “text” name= “firstname”/>
Lastname: <input type= “text” name= “age”/>
Age: <input type= “text” name= “age”/>
<input type= “submit”/>
</form>
</body>
</html>

When a user clicks the submit button in the HTML form in the example above, the form data is sent to “insert.php”.

The “inset.php” file connects to a database, and retrieves the values from the form with the PHP $_POST variables.

Then, the mysql_query( ) function executes the INSERT INTO statement, and a new record will be added to the “Persons” table.

Here is the “insert.php” page:
<?php
$con= mysql_connect(“localhost”, “peter”, “abc123”);
if (!$con)
{
die(‘Could not connect:’. mysql_error());
}
mysql_select_db(“my_db”, $con))
$sql= “INSERT INTO Persons (FirstName, LastName, Age)

VALUES
(‘$_POST[firstname]’, ‘$_POST[lastname]’, ‘$_POST[age]’)”;
if (!mysql_query($sql,$con))
{
die(‘Error:’. mysql_error());
}
echo “1 record added”;
mysql_close($con)
?>

10. Select Data From a Database Table:
The SELECT statement is used to select data from a database.

Syntax:  
SELECT column_name(s)
FROM table_name

To get PHP to execute the statement above we must use the mysql_quert( ) function. This function is used to send a query or command to a MySQL connection.

Example: The following example selects all the data stored in the “Person’s” table (The * character selects all the data in the table):
<?php
$con= mysql_connect(“localhost”, “peter”, “abc123”);
if (!$con)
{
die(‘Could not connect:’. mysql_error( ));
}
mysql_select_db(“my_db”, $con);
$result= mysql_query(“SELECT * FROM Persons”);
while($row= mysql_fetch_array($result))
{
echo $row[‘FirstName’]. “”. $row[‘LastName’];
echo “<br/>”;
}
mysql_close($con);
?>

The example above stores the data returned by the mysql_query( ) function in the $result variable. Next, we use the mysql_fetch_array( ) function to return the first row from the recordset as an array. Each call to mysql_fetch_array( ) returns the next row in the recordset. The while loop loops through all the records in the recordset. To print the value of each row, we use the PHP $row variable ($row[‘FirstName’] and $row[‘LastName’]).

The output of the code above will be:
Peter Griffin
Glenn Quagmire

11. Display the Result in an HTML Table:
The following example selects the same data as the example above, but will display the data in an HTML table:

<?php
$con= mysql_connect(“localhost”, “peter”, “abc123”);
if (!$con)
{
die(‘Could not connect:’ . mysql_error( ));
}
mysql_select_db(“my_db”, $con);
$result= mysql_query(“SELECT * FROM Persons”);
echo “<table border= ‘1’>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>”;
while($row= mysql_fetch_array($result))
{
echo “<tr>”;
echo “<td>”. $row[‘FirstName’]. “</td>”;
echo “<td>”. $row[‘LastName’]. “</td>”;
echo “</tr>”;
}
echo “</table>”;
mysql_close($con);
?>

The output of the code above will be:

FirstnameLastname
GlennQuagmire
PeterGriffin

12. The WHERE clause:
The WHERE clause is used to extract only those records that fulfill a specified criterion.

Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name operator value

To get PHP to execute the statement above, we must use the mysql_query( ) function. This function is used to send a query or command to a MySQL connection.

Example: The following example selects all rows from the “Persons” table where “FirstName= ‘Peter’:
<?php
$con= mysql_connect(“localhost”, “peter”, “abc123”);
if (!$con)
{
die(‘Could not connect:’. mysql_error());
}
mysql_select_db(“my_db”, $con)
$result= mysql_query(“SELECT * FROM Persons
WHERE FirstName= ‘Peter’”);
while($row= mysql_fetch_array($result))
{
echo $row[‘FirstName’]. “”. $row[‘LastName’];
echo “<br/>”;
}
?>

The output of the code above will be:

Peter Griffin

13. The ORDER BY Keyword:
The ORDER BY keyword is used to sort the data in a recordset. The ORDER BY keyword sort the records in ascending order by default. If one want to sort the records in descending order, one can use the DESC keyword.

Syntax:
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC

Example: The following example selects all the data stored in the “Person’s” table, and sorts the result by the “Age” column:
<?php
$con= mysql_connect(“localhost”, “peter”, “abc123”);
if (!$con)
{
die(‘Could not connect:’. mysql_error());
}
mysql_select_db(“my_db”, $con);
$result= mysql_query(“SELECT * FROM Persons ORDER BY age”);
while($row = mysql_fetch_array($result))
{
echo $row[‘FirstName’];
echo “”. $row[‘LastName’];
echo “”. $row[‘Age’];
echo “<br/>”;
}
mysql_close($con);
?>

The output of the code above will be:

Glenn Quagmire 33
Peter Griffin 35

14. Order by Two Columns:
It is also possible to order by more than one column. When ordering by more than one column, the second column is only used if the values in the first column are equal:

SELECT column_name(s)
FROM table_name
ORDER BY column1, column2

15. Update Data In a Database:
The UPDATE statement is used to update existing records in a table:

Syntax: 
UPDATE table_name
SET column1=value, column2=value2,…
WHERE some_column=some_value

Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated! To get PHP to execute the statement above we must use the mysql_query( ) function. This function is used to send a query or command to a MySQL connection.

Example: Earlier in the chapter we created a table named “Persons”. Here is how it looks:

FirstName        LastName        Age

Peter                 Griffin                35

Glenn                Quagmire          33 

The following example updates some data in the “Persons” table:
<?php
$con= mysql_connect(“localhost”, “peter”, “abc123”);
if (!$con)
{
die(‘Could not connect:’. mysql_error( ));
}
mysql_select_db(“my_db”, $con);
mysql_query(“UPDATE Persons SET Age= ‘36’
WHERE FirstName = ‘Peter’ AND LastName = ‘Griffin’”);
mysql_close($con);
?>

After the update, the “Persons” table will look like this:

FirstName        LastName        Age

Peter                 Griffin                36

Glenn                Quagmire          33 

16. Delete Data In a Database:
The DELETE FROM statement is used to delete records from a database table.

Syntax:
DELETE FROM table_name
WHERE some_column= some_value

Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or records that should be deleted. By omitting the WHERE clause, all records will be updated! To get PHP to execute the statement above we must use the mysql_query( ) function. This function is used to send a query or command to a MySQL connection.

Example: Look at the following “Persons” table:

FirstName        LastName        Age

Peter                 Griffin                35

Glenn                Quagmire          33 

The following example deletes all the records in the “Persons” table where LastName= ‘Griffin’:
<?php
$con= mysql_connect(“localhost”, “peter”, “abc123”);
if (!$con)
{
die(‘Could not connect:’. mysql_error( ));
}
mysql_select_db(“my_db”, $con);
mysql_query(“DELETE FROM Persons WHERE LastName= ‘Griffin’”);
mysql_close($con);
?>

After the deletion, the table will look like this: 

FirstName        LastName        Age

Glenn                Quagmire          33 

PHP Database ODBC:

ODBC is an Application Programming Interface (API) that allows users to connect to a data source (e.g. an MS Access database).

  1. Create an ODBC Connection:
    With an ODBC connection, one can connect to any database, on any computer in the network, as long as an ODBC connection is available. Here is how to create an ODBC connection to a MS Access Database:

(i) open the Administrative Tools icon in your Control Panel.
(ii) Double-click on the Data Sources (ODBC) icon inside.
(iii) Choose the System DSN tab.
(iv) Click on Add in the System DSN tab.
(v) Select the Microsoft Access Driver. Click Finish.
(vi) In the next screen, click Select to locate the database.
(vii) Give the database a Data Source Name (DSN).
(viii) Click OK.

Note that this configuration has to be done on the computer where the web site is located. If there is an Internet Information Server (IIS) on the computer, then instructions above will work, but if the web site is located on a remote server, have physical access to that server, or ask the web host to set up a DSN to use.

  1. Connecting to an ODBC:
    The odbc_connect( ) function is used to connect to an ODBC data source. The function takes four parameters: the data source name, username, password, and an optional cursor type. The odbc_exec( ) function is used to execute an SQL statement.

Example: The following example creates a connection to a DSN called northwind, with no username and no password. It then creates an SQL and executes it:
$conn=odbc_connect(‘northwind’, “,”);
$SQL=”SELECT * FROM customers”;
$rs=odbc_exec($conn,$sql);

  1. Retrieving Records:
    The odbc_fetch_row( ) function is used to return records from the result-set. This function returns true if it is able to return rows, otherwise false. The function takes two parameters: the ODBC result identifier and an optional row number:

odbc_fetch_row($rs)

  1. Retrieving Fields from a Record:
    The odbc_result( ) function is used to read fields from a record. This function takes two parameters: the ODBC result identifier and a field number or name. The code line below returns the value of the first field from the record:

$compare=odbc_result($rs,1);
The code line below returns the value of a field called “CompanyName”:
$compname=odbc_result($rs,”CompanyName”);

  1. Closing an ODBC Connection:
    The odbc_close( ) function is used to close an ODBC connection.

An ODBC Example: The following example shows how to first create a database connection, then a result-set, and then display the data in an HTML table.

<html>
<body>
<?php
$conn=odbc_connect(‘northwind’, “,”);
if (!$conn)
{exit(“Connection Failed:”. $conn);}
$sql= “SELECT * FROM customers”;
$rs=odbc_exec($conn.$sql);
if (!$rs)
exit(“Error in SQL”);}
echo “<table><tr>”;
echo “<th>Companyname</th>”;
echo “<th>Contactname</th></tr>”;
while (odbc_fetch_row($rs))
{
$compname=odbc_result($rs, “CompanyName”);
$conname=odbc_result($rs, “Contactname”);
echo “<tr><td>$compname</td>”;
echo “<td>$conname</td></tr>”;
}
odbc_close($conn);
echo “</table>”;
?>
</body>
</html>

Source: I&WT, Wikipedia

Our Suggested Article’s
ADVANTAGES AND DISADVANTAGES OF GADGETS IN OUR LIFE
What To Do If Mobile Is Stolen??
How To Choose Best Mobile Camera
How To Choose Best Processor For Mobile??
Best Top Ten Printers For Home & Office Use In 2020
How To Send Stickers In WhatsApp??
What Is Domain Name Servers?What Is Ip Address?? And Ip Address ClassesWhat Is A Modem? & Types Of ModemBest Wireless Earphones Under Rs 2000 -Tested & ReviewedConnecting To The Internet In Windows PcWhat Is Internet Definition And Evolution Of The Internet
Ten Best Bluetooth Earphones Under 1000 Rupees -Tested & ReviewedTen Best Wireless Mouse Under 1000 Rupees – Tested & ReviewedThe Best Mouse Under 500 Rupees – Tested And ReviewedBest Wireless Mouse Under 500 Rupees – Tested And Reviewed

Leave a Comment