phpmysqlu1.1

 

Unit – I

Introducing PHP

What Is PHP ?

·         PHP is a programming language for building dynamic, interactive Web sites.

·         PHP programs run on a Web server, and serve Web pages to visitors on request.

·         One of the key features of PHP is that you can embed PHP code within HTML Web pages, making it very easy for you to create dynamic content quickly.

·         A dynamic Web page is a page whose contents can change automatically each time the page is viewed.

·         Astatic Web page, such as a simple HTML file, which looks the same each time it ’ s displayed .

·         PHP stands for PHP: Hypertext Preprocessor.

·         PHP is a server - side scripting language , which means that PHP scripts, or programs, usually run on a Web server.

·         PHP is an interpreted language — a PHP script is processed by the PHP engine each time it ’ s run.


The process of running a PHP script on a Web server looks like this:

1. A visitor requests a Web page by clicking a link, or typing the page ’ s URL into the browser ’ s address bar. The visitor might also send data to the Web server at the same time, either using a form embedded in a Web page, or via AJAX (Asynchronous JavaScript And XML).

2. The Web server recognizes that the requested URL is a PHP script, and instructs the PHP engine to process and run the script.

3. The script runs, and when it ’ s finished it usually sends an HTML page to the Web browser, which the visitor then sees on their screen.

A PHP script can carry out any number of interesting tasks, such as:

·         Reading and processing the contents of a Web form sent by the visitor

·         Reading, writing, and creating files on the Web server

·         Working with data in a database stored on the Web server

·         Grabbing and processing data from other Web sites and feeds

·         Generating dynamic graphics, such as charts and manipulated photos

And finally, once it ’ s finished processing, it can send a customized HTML Web page back to the visitor.

 

Why Use PHP ?

·         PHP is cross - platform .

·         PHPsupports large number of Internet service providers (ISPs) and Webhosting companies .

·         PHP engine can integrate with all common Web servers, including Apache, Internet Information Server (IIS), Zeus, and lighttpd.

PHP compare with other common Web programming technologies:

ASP (Active Server Pages) ,ASP.NET ,Perl ,Java ,Python ,Ruby ,ColdFusion

The Evolution of PHP

PHP was created byRasmus Lerdorf way back in 1994. He released PHP to the general public in 1995, and called it PHP version 2.

In 1997, two more developers, Zeev Suraski and Andi Gutmans, rewrote most of PHP and, along withRasmus, released PHP version 3.0 in June 1998.

For the next version of PHP, Zeev and Andi set about rewriting the PHP core yet again, calling it the“ Zend Engine ” (basing the name “ Zend ” on their two names). The new version, PHP 4, was launched inMay 2000.

PHP 5, released in July 2004, addressed some issues, withprivate and protected class members; final, private, protected, and static methods; abstract classes;interfaces; and a standardized constructor/destructor syntax.

Installing PHP

To create and run PHP scripts, you need to have a few things in place:

·         A computer running Web server software, such as Apache or Internet Information Server (IIS)

·         The PHP server module installed on the same computer. This module talks to the Web serversoftware; this is the PHP engine that actually does the work of running your PHP scripts

·         If you want to build database - driven Web applications — and you probably will — you alsoneed a database server installed. Options include MySQL, PostgreSQL, and SQL Server.

For example, operating systems that can run PHP include Linux, Windows, and Mac OS X,and Web server software includes Apache, IIS, and Zeus.



Installing on Windows

PHP on Windows can work with Apache or IIS. WampServer(Windows, Apache, MySQL, and PHP) this handy piece of software gives you Apache,MySQL, and PHP all in one handy, easy - to - install package.

To install WampServer, follow these steps:

1. Download the latest version of WampServer from http://www.wampserver.com/en/ .

2. Open the WampServer .exe file that you downloaded, and follow the instructions on the screen to install the application.

3. Unblock Apache. As you run the installer, you may be asked if you want to allow Apache through the Windows Firewall. If you want to allow other computers onyour network to access the Web server, click Unblock. If you ’ re only going to access the Webserver from a browser on the same computer, you can click Keep Blocking to improve security.

4. Enter default mail settings. During the configuration process you ’ ll also be asked to enter a default mail server and email address for PHP to use (Figure 3.1 ); you can accept the defaults for now.

5.Once the setup wizard has completed, you should see a WampServer icon in your taskbar; click this icon to display the WampServer menu . Choose the Start All Services option to fire up the Apache and MySQL servers.

6. To test that the Web server is running correctly, choose the Localhost option from the WampServer menu. If all has gone according to plan, you should see the page shown in Figure 3.2 appear; this means that WampServer was successfully installed. Congratulations !Move on to the “ Testing Your Installation ” section of this chapter to make sure everything is working OK.

Testing Your Installation

Now that you ’ ve installed Apache, PHP, and MySQL on your computer, you ’ re ready to test the installation .

Testing the Web Server

The first thing to do is to create a simple HTML Web page for testing. In a text editor such as Notepad for Windows, TextEdit on the Mac, or vi/emacs/pico on Linux, create the following simple Web page:

<html>

<head>

<title>Testing</title>

</head>

<body>

<h1>Testing, testing, 1-2-3</h1>

</body>

</html>

Call the Web page testing.html and save it in your Web server ’ s document root folder on your hard drive.

·         If you ’ ve installed Apache on Ubuntu Linux, the document root folder is probably /var/www.

·         With WampServer on Windows, the document root folder is usually in C:\wamp\www.

·         So save your testing.html file to the appropriate folder, and then open a Web browser and type the following into its address bar:

http://localhost/testing.html

Testing PHP

Open your text editor again, and create a new file with the following contents:

< ?php

phpinfo();

? >

Save this file as testing.php in the same folder as your testing.html file — that is to say, the document root folder. Now type the following into your Web browser ’ s address bar .

http://localhost/testing.php

Press Enter, This is the result of running the phpinfo() function, a built - in PHP function that displays information about the version of PHP that ’ s installed. This means that you have successfully installed both Apache and PHP.



Creating Your First Script

< ?php

echo “Hello, world!”;

? >

Save this file as hello.php in your document root folder, and view the results in your browser byvisiting http://localhost/hello.php.

 

< ?php

By using the PHP delimiter, < ?php, you ’ re telling the PHP engine to treat anything following the < ?php as PHP code, rather than as HTML. The first line tells that PHP can be embedded within HTML Web pages.

The next line displays the message “ Hello, world! ” :

echo “Hello, world!”;

 

PHP ’ s echo() can display anything that can be displayed, such as numbersor the results of expressions.

In this case, “Hello, world!” .

An alternative to echo() is the print() statement.

The final line of your simple script tells the PHP engine that it ’ s reached the end of the current section ofPHP code, and that the following lines (if any) contain plain HTML again:

? >

 

Embedding PHP within HTML

<html>

<head>

<title>Hello</title>

<link rel=”stylesheet” type=”text/css” href=”common.css” />

</head>

<body>

<h1><?php echo “Hello, world!”; ?></h1>

</body>

</html>

common.css

/* Page body */

body { font-family: Arial, Helvetica, sans-serif; }

/* Headings */

h1 { font-weight: bold; margin: 35px 0 14px; color: #666; font-size: 1.5em; }

Run your new PHP script by typing http://localhost/hello_pretty.php

 

Using Comments to Make Code More Readable

single - line comment

// This code displays the current time

# This code displays the current time

multi - line comments

/*This code displays the

current time in a nice,

easy-to-read format.

*/

PHP Language Basics

·         Variables , which let you store and manipulate data in your scripts

·         Data types , including which types are available in PHP, and how to test for and change type

·         PHP ’ s available operators , which you can use to manipulate information

·         Constants , which are useful for storing data that doesn’ t change in your script.

 

Using Variables in PHP

A variable is simply a container that holds a certain value. Variables get their name because that certain value can change throughout the execution of the script.

Naming Variables

A variable consists of two parts: the variable ’ s name and the variable ’ s value.

·         Variable names begin with a dollar sign ( $ )

·         The first character after the dollar sign must be a letter or an underscore

·         The remaining characters in the name may be letters, numbers, or underscores without a fixed limit

·         Variable names are case - sensitive ( $Variable and $variable are two distinct variables)

 

Here are some examples of PHP variable names:

$my_first_variable

$anotherVariable

$x

$_123

 

Creating Variables

Creating a variable in PHP is known as declaring it. Declaring a variable is as simple as using its name in your script:

$my_first_variable;

Here ’ s an example of declaring and initializing a variable:

$my_first_variable = 3;

$x = 5;

$y = 6;

echo $x + $y;   // outputs their sum ( 11 ):

 

Understanding Data Types

PHP supports four scalar data types. Scalar data means data that contains only a single value. Here ’ s a list of them,

PHP supports two compound types. Compound data is data that can contain more than one value. The following table describes PHP ’ s compound types,PHP supports two special data types.

 

About Loose Typing

PHP  converts a variable ’ s data type automatically, depending on the context in which the variable is used. For example, you can initialize a variable with an integer value; add a float value to it, thereby turning it into a float; then join it onto a string value to produce a longer string.

 

Testing the Type of a Variable

You can determine the type of a variable at any time by using PHP ’ s gettype() function. To use gettype() , pass in the variable whose type you want to test. The function then returns the variable ’ s type as a string.

$test_var; // Declares the $test_var variable without initializing it

echo gettype( $test_var ) . “ <br/> ”;           // Displays “NULL”

$test_var = 15;

echo gettype( $test_var ) . “ <br/> ”;           // Displays “integer”

$test_var = 8.23;

echo gettype( $test_var ) . “ <br/> ”;           // Displays “double”

$test_var = “Hello, world!”;

echo gettype( $test_var ) . “ <br/> ”;           // Displays “string”

 

Changing a Variable ’ s Data Type

Use PHP ’ s settype() function to change the type of a variable while preserving the variable ’ s value as much as possible. To use settype() , pass in the name of the variable you want to alter, followed by the type to change the variable to (in quotation marks).

Here ’ s some example code that converts a variable to various different types using settype() :

$test_var = 8.23;

echo $test_var . “ <br/> ”;                // Displays “8.23”

 

settype( $test_var, “string” );

echo $test_var . “ <br/> ”;                // Displays “8.23”

 

settype( $test_var, “integer” );

echo $test_var . “ <br/> ”;                // Displays “8”

 

settype( $test_var, “float” );

echo $test_var . “ <br/> ”;                // Displays “8”

 

settype( $test_var, “boolean” );

echo $test_var . “<br/>”// Displays “1”  (PHP converts a non - zero number to the Boolean value true.)

 

Changing Type by Casting

You can also cause a variable ’ s value to be treated as a specific type using a technique known as type casting . This involves placing the name of the desired data type in parentheses before the variable ’ s name. Note that the variable itself remains unaffected; this is in contrast to settype() , which changes the variable ’ s type.

$test_var = 8.23;

echo $test_var . “ <br/> ”;                // Displays “8.23”

 

echo (string) $test_var . “ <br/> ”;   // Displays “8.23”

 

echo (int) $test_var . “ <br/> ”;        // Displays “8”

 

echo (float) $test_var . “ <br/> ”;     // Displays “8.23”

 

echo (boolean) $test_var . “ <br/> ”;           // Displays “1”

Note that $test_var ’ s type isn ’ t changed at any point; it remains a floating - point variable, containing the value 8.23 , at all times. All that changes is the type of the data that ’ s passed to the echo statement.

 

Operators and Expressions

Arithmetic Operators

For example, $c = $a + $b adds $a and $b

and assigns the result to $c .

 Assignment Operators



The basic assignment operator ( = ) can be used to assign a value to a variable:

$test_var = 8.23;

 

$another_var = $test_var = 8.23;

So both $test_var and $another_var now contain the value 8.23

 

For example, you can write:

$first_number += $second_number;

rather than:

$first_number = $first_number + $second_number;

 

 

For example, the concatenation operator can be combined with the equals sign (as .= ), causing the value on the right side to beappended to the existing value on the left, like this:

$a = “Start a sentence “;

$b = “and finish it.”;

$a .= $b; // $a now contains “ Start a sentence and finish it. ”

 

Bitwise Operators



Incrementing /Decrementing Operators

Oftentimes it ’ s useful to add or subtract the value 1 (one) over and over.

++$x;               // Adds one to $x and then returns the result

$x++;               // Returns $x and then adds one to it

– - $x;              // Subtracts one from $x and then returns the result

$x – - ;                         // Returns $x and then subtracts one from it

The location of the operators makes a difference. Placing the operator before the variable name causes the variable ’ s value to be incremented or decremented before the value is returned; placing the operator after the variable name returns the current value of the variable first, then adds or subtracts one from the variable. For example:

$x = 5;

echo ++$x; // Displays “6” (and $x now contains 6)

$x = 5;

echo $x++; // Displays “5” (and $x now contains 6)

 

Comparison Operators

If the comparison test is successful, the expression evaluates to true ; otherwise, it evaluates to false .



 

Logical Operators

PHP ’ s logical operators work on Boolean values. Boolean value is either true or false . PHP automatically evaluates expressions as either true or false.

 



Here are some simple examples of logical operators in action:

$x = 2;

$y = 3;

echo ( ($x > 1) && ($x < 5) ) . “ <br/> ”;                 // Displays 1 (true)

echo ( ($x == 2) or ($y == 0) ) . “ <br/> ”;               // Displays 1 (true)

echo ( ($x == 2) xor ($y == 3) ) . “ <br/> ”; // Displays “” (false) because bothexpressions are true

echo ( !($x == 5 ) ) . “ <br/> ”;          // Displays 1 (true) because$x does not equal 5

 

String Operators

There ’ s really only one string operator, and that ’ s the concatenation operator , . (dot). This operator simply takes two string values, and joins the right - hand string onto the left - hand one .

For example:

echo “Hello, “ . “How are you”;                  // Displays “ Hello, How are you ”

For example, the following two lines of code change the string variable $x by adding the string variable $y to the end of it.

$x = $x . $y;

$x .= $y;

 

Constants

·         The values of constants, as their name implies, can never be changed. Constants can be defined only once in a PHP program.

·         Constants differ from variables in that their names do not start with the dollar sign, but other than that they can be named in the same way variables are. However, it ’ s good practice to use all - uppercase names for constants.

·         To define a constant, use the define() function, and include inside the parentheses the name you ’ ve chosen for the constant, followed by the value for the constant, as shown here:

define( “MY_CONSTANT”, “19” ); // MY_CONSTANT always has the string value “ 19 ”

echo MY_CONSTANT; // Displays “ 19 ” (note this is a string, not an integer)

 

Calculate the Properties of a Circle

< ?php

$radius = 4;

$diameter = $radius * 2;

$circumference = M_PI * $diameter;

$area = M_PI * pow( $radius, 2 );

echo “This circle has... <br/> ”;

echo “A radius of “ . $radius . “ <br/> ”;

echo “A diameter of “ . $diameter . “ <br/> ”;

echo “A circumference of “ . $circumference .“<br/> ”;

echo “An area of “ . $area . “ < br / > ”;

?>


 



Decisions and Loops

Making Decisions

PHP gives you a number of statements that you can use to make decisions:

 

if Statement

The basic form of an if construct is as follows:

if ( expression ) {

// Run this code

}

// More code here

If the expression inside the parentheses evaluates to true , the code between the braces is run. If the expression evaluates to false , the code between the braces is skipped.

 







If-else Statement

You can enhance this decision - making process by adding an else statement to an if construction. This lets you run one block of code if an expression is true , and a different block of code if the expression is false . For example:



elseif Statement

Used to combine an else and an if statement.



switch Statement

Sometimes you want to test an expression against a range of different values, carrying out a different task depending on the value that is matched.


PHP provides a more elegant way to run these types of tests: the switch statement. With this statement,

you include the expression to test only once, then provide a range of values to test it against, with corresponding code blocks to run if the values match.

 


Doing Repetitive Tasks with Looping

·         while loops

·         do...while loops

·         for loops

while Statement

while ( expression ) {

// Run this code

}

// More code here

 

The expression inside the parentheses is tested; if it evaluates to true , the code block inside the braces is run. Then the expression is tested again; if it ’ s still true , the code block is run again, and so on. However, if at any point the expression is false , the loop exits and execution continues with the line after the closing brace.

< ?php

$mobilesLeft = 10;

while ( $mobilesLeft > 0 ) {

echo “Selling  mobiles... “;

$mobilesLeft - - ;

echo “done. There are $mobilesLeft mobiles left. <br/> ”;

}

echo “We ’ re right out of mobiles!”;

?>

The do . . . while Loop

Sometimes it ’ s useful to be able to run the code in the loop at least once before checking the expression, and this is exactly what do...while loops do.

<?php

$width = 1;

$length = 1;

do {

$width++;

$length++;

$area = $width * $length;

} while ( $area < 1000 );

echo “The smallest square over 1000 sq ft in area is $width ft x $length ft.”;

?>

 

The for Statement

The for statement is a bit more complex than do and do...while , but it ’ s a neat and compact way to

write certain types of loops.

for ( expression1; expression2; expression3 ) {

// Run this code

}

// More code here

For loop can contain three expressions. These expressions, in order, are:

The initializer expression — This is run just once, when the for statement is first encountered.Typically, it ’ s used to initialize a counter variable (for example, $counter = 1 )

The loop test expression — This fulfils the same purpose as the single expression in a do ordo...while loop. If this expression evaluates to true , the loop continues; if it ’ s false , the loopexits. An example of a loop test expression would be $counter < = 10

The counting expression — This expression is run after each iteration of the loop, and is usuallyused to change the counter variable — for example, $counter++

 

for ( $i = 1; $i < = 10; $i++ ) {

echo “I ’ ve counted to: $i <br/> ”;

}

echo “All done!”;

 

Escaping from Loops with the break Statement

Normally, a while , do...while , or for loop will continue looping as long as its test expression evaluates to true . However, you can exit a loop at any point while the loop ’ s executing by using the break statement.

$count = 0;

while ( true ) {

$count++;

echo “I ’ ve counted to: $count < br / > ”;

if ( $count == 10 ) break;

}

 

Skipping Loop Iterations with the continue Statement

Continue lets you prematurely end the current iterationof a loop and move onto the next iteration. This can be useful if you want to skip the current item of datayou ’ re working with; maybe you don ’ t want to change or use that particular data item, or maybe thedata item can ’ t be used for some reason .

for ( $i=1; $i < = 10; $i++ ) {

if ( $i == 4 ) continue;

echo “I ’ ve counted to: $i < br / > ”;

}

echo “All done!”;

 

Creating Nested Loops

There ’ s nothing to stop you creating a loop inside another loop.

 

Mixing Decisions and Looping with HTML

 

We can switch between displaying HTML markup and executing PHP code byusing the < ?php ... ? > tags. This feature really comes into its own with decisions and looping, because you can use PHP to control which sections of a Web page are displayed.

 

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en” >

<head>

<title> Even or Odd Number</title>

</head>

<body>

<?php

for ($i = 1;$i <= 100;$l++)

{

    if ($i%2 == 0)

 {

        echo "<br>$i is Even number";

    }

 

else {

        echo "<br> $i is Odd Number";

    }

}

?>

</body>

</html>

Save this file as EvenOdd.php in your document root folder and running the script in your browser.

Next Topic -Strings

No comments:

Post a Comment