Sie sind auf Seite 1von 44

Confused In Languages

c/c++ VB /VB.Net Java ASP /JSP / PHP ASP.Net VB Script /Java Script CSS

INTRODUCTION TO PHP
Server-Side Scripting MySQL PHP Apache Variables Control Structure Looping

Server-Side Scripting

A script is a collection of program or sequence of instructions that is interpreted or carried out by another program rather than by the computer processor.
Client-side Server-side

In server-side scripting, (such as PHP, ASP) the script is processed by the server Like: Apache, ColdFusion, ISAPI and Microsoft's IIS on Windows. Client-side scripting such as JavaScript runs on

Server-Side Scripting Continued

Advantages of Server-Side Scripting Dynamic content. Computational capability. Database and file system access. Network access (from the server only). Built-in libraries and functions. Known platform for execution (as opposed to client-side, where the platform is uncontrolled.) Security improvements

Introduction to PHP

PHP stands for PHP: Hypertext Preprocessor Developed by Rasmus Lerdorf in 1994 It is a powerful server-side scripting language for creating dynamic and interactive websites. It is an open source software, which is widely used and free to download and use (PHP is FREE to download from the official PHP resource: www.php.net). It is an efficient alternative to competitors such as Microsoft's ASP.

Introduction to PHP

PHP is perfectly suited for Web development and can be embedded directly into the HTML code. The PHP syntax is very similar to JavaScript, Perl and C. PHP is often used together with Apache (web server) on various operating systems. It also supports ISAPI and can be used with Microsoft's IIS on Windows. PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL,

Introduction to PHP

What is a PHP File?


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

Introduction to PHP
What you need to develop PHP Application: Install Apache (or IIS) on your own server, install PHP, and MySQL OR Install Wampserver2 (a bundle of PHP, Apache, and MySql server) on your own server/machine

PHP Installation Downloads


Free Download PHP: http://www.php.net/downloads.php MySQL Database: http://www.mysql.com/downloads/index.html Apache Server: http://httpd.apache.org/download.cgi

How to install and configure apache Here is a link to a good tutorial from PHP.net on how to install PHP5: http://www.php.net/manual/en/install.php

How PHP is Processed

When a PHP document is requested of a server, the server will send the document first to a PHP processor Two modes of operation

Copy mode in which plain HTML is copied to the output Interpret mode in which PHP code is interpreted and the output from that code sent to output The client never sees PHP code, only the output produced by the code

Basic PHP Syntax


PHP statements are terminated with semicolons ; Curly braces, { } are used to create compound statements Variables cannot be defined in a compound statement unless it is the body of a function PHP has typical scripting language characteristics

Dynamic typing, un-typed variables Associative arrays Pattern matching Extensive libraries

Primitives, Operations, Expressions


Four scalar types: boolean, integer, double, string Two compound types: array, object Two special types: resource and NULL

Basic PHP Syntax

A PHP scripting block always starts with <?php and ends with ?> <?php . ?>
1. 2.

Other options are: <? ?> <script> ... </script>

There are three basic statements to output text with PHP: echo, print, and printf. Example:
echo 'This is a <b>test</b>!';

Comments:

# // /* . . . */

Basic PHP Syntax


Inserting external files: PHP provides four functions that enable you to insert code from external files: include() or require() include_once() or require_once() functions.

E.g.
include("table2.php");

Included files start in copy mode

Basic PHP Syntax


Example 1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Simple PHP Example</title>

<body>

<?php
echo "Hello Class of 2013. This is my first PHP Script"; echo "<br />"; print "<b><i>What have you learnt and how many friends have you made?</i></b>"; echo "<br /><a href='PHP I-BSIC.ppt'>PHP BASIC</a>";

?> </body> </html>

PHP Variables

Example:
<html>

<head>
<title>My first PHP page</title> </head>

Variables are used for storing values, such as numbers, strings or function results, so that they can be used many times in a script. All variables in PHP start with a $ sign symbol. Variables are assigned using the assignment operator "="

<body>

<?php $var1 = 'PHP'; // Assigns a value of 'PHP' to


$var1

Variable names are case sensitive in PHP: $name is not the same as $NAME or $Name.
In PHP a variable does not need to be declared before being set.

$var2 = 5; // Assigns a value of 5 to $var2 $var3 = $var2 + 1; // Assigns a value of 6 to $var3 $var2 = $var1; // Assigns a value of 'PHP' to $var2 echo $var1; // Outputs 'PHP echo "<br />"; echo $var2; // Outputs 'PHP' echo "<br />"; echo $var3; // Outputs '6' echo "<br />"; echo $var1 . ' rules!'; // Outputs 'PHP rules!' echo "$var1 rules!"; // Outputs 'PHP rules!' echo '$var1 rules!'; // Outputs '$var1 rules! ?>

</body>

Variable Naming Rules

A variable name must start with a letter or an underscore "_" A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ ) If variable name is more than one word, it should be separated with an underscore e.g. ($my_string), or with capitalization ($myString)

Variable Scope and Lifetime


Example:

The scope of a variable defined within a function is local to that function. A variable defined in the main body of code has a global scope.

If a function needs to use a variable that is defined in the main body of the program, it must reference it using the "global"

<?php function mul() { global $start; print "<tr>"; for ($num=1; $num <= 10; $num++ ) { $cell = $num * $start; print "<td> " . $cell . " </td>"; } print "</tr>"; } $start = 0; print "<table border=1 cellpadding=3>"; while ( $start <=10 ) { mul(); $start++; } print "</table>"; ?>

Strings in PHP

a string is a sequence of letters, symbols, characters and arithmetic values or combination of all tied together in single or double quotes. String literals are enclosed in single or double quotes Example:
<?php $sum = 20; echo 'the sum is: $sum'; echo "<br />"; echo "the sum is: $sum"; echo "<br />"; echo '<input type="text" name="first_name" id="first_name">'; ?>

Double quoted strings have escape sequences (such as /n or /r) interpreted and variables interpolated (substituted) Single quoted strings have neither escape sequence interpretation nor variable interpolation A literal $ sign in a double quoted string must be escaped with a backslash, \ Double-quoted strings can cover multiple lines

Escaping quotes with in quotes


Example 1:
<?php $str = "\"This is a PHP string examples quotes\""; echo $str; ?>

Example 2
<?php $str = 'It\'s a nice day today.'; echo $str; ?>

The Concatenation Operator

The concatenation operator (.) is used to put two string values together. Example:
<?php $txt1="Hello Everyone,"; $txt2="1234 is Dans home address"; echo $txt1.$txt2; ?>

PHP Operators

Operators are used to operate on values. List of PHP Operators:

PHP Function

In php a function is a predefined set of commands that are carried out when the function is called. The real power of PHP comes from its functions. PHP has more than 700 built-in or predefine functions for you to use.
Complete

php string reference

You can write your own functions

Using Built-in Fuctions

Useful PHP String Functions

Example - strlen() Function


<?php $str = "Hello world!"; echo strlen($str); ?> Example - strlen() Function
<?php $str = Hello world!; echo strpos($str,"world"); ?> </body> </html>

Useful PHP String Functions <?php echo strlen("Hello world!"); echo "<br />"; echo strpos("Hello world!","world"); ?> </body> </html>

Using Built-in Function


<html> <head> <title>My first PHP page</title> </head> <body> <?php $a = abs(-.43); $b = sqrt(16); $c = round(12.3); print "The absolute value of -.43 is " . $a . "<br />"; print "The square root of 16 is " . $b . "<br />"; print "12.3 rounded is " . $c . " and 12.5 rounded is " . round(12.5); ?> </body> </html>

Using Built-in Function


Examples: Inserting external files: PHP provides four functions that enable you to insert code from external files: include() or require() include_once() or require_once() functions. Using the include function <?php include('add.php'); echo add(2, 2); ?>

A sample include file called add.php <html> <body>

<?php function add( $x, $y ) { return $x + $y; } ?>


<h1>Welcome to my home page</h1> <p>Some text</p> </body> </html>

Using Built-in Function


Inserting external files - continued: The functions are identical in every way, except how they handle errors.

The include() and include_once() functions generates a warning (but the script will continue execution) The require() and require_once() functions generates a fatal error (and the script execution will stop after the error).

These functions are used to create functions, headers, footers, or elements that can be reused on multiple pages.

This can save the developer a considerable amount of time for updating/editing.

Date Function Formatting DAYS d - day of the month 2 digits (01-31) j - day of the month (1-31) D - 3 letter day (Mon - Sun) l - full name of day (Monday - Sunday) N - 1=Monday, 2=Tuesday, etc (1-7) S - suffix for date (st, nd, rd) w - 0=Sunday, 1=Monday (0-6) z - day of the year (1=365) WEEK W - week of the year (1-52) MONTH F - Full name of month (January - December) m - 2 digit month number (01-12) n - month number (1-12) M - 3 letter month (Jan - Dec) t - Days in the month (28-31) YEAR L - leap year (0 no, 1 yes) o - ISO-8601 year number (Ex. 1979, 2006) Y - four digit year (Ex. 1979, 2006) y - two digit year (Ex. 79, 06)

Date Function Formatting TIME a - am or pm A - AM or PM B - Swatch Internet time (000 - 999) g - 12 hour (1-12) G - 24 hour c (0-23) h - 2 digit 12 hour (01-12) H - 2 digit 24 hour (0023) i - 2 digit minutes (00-59) s 0 2 digit seconds (0059) OTHER e - timezone (Ex: GMT, CST) I - daylight savings (1=yes, 0=no) O - offset GMT (Ex: 0200) Z - offset in seconds (43200 - 43200)

Using Built-in Function


PHP Date() function formatting characters:
Example 2

Example 1:

<?php $theDate = date("m/d/y"); echo "Today's date is: $theDate"; ?>

<?php $b = time (); print date("m/d/y",$b) . "<br />"; print date("D, F jS",$b) . "<br />"; print date("l, F jS Y",$b) . "<br />"; print date("g:i A",$b) . "<br />"; print date("r",$b) . "<br />"; print date("g:i:s A D, F jS Y",$b) . "<br />"; ?>

Defining and Referencing a Function


Syntax function functionname () { your code } Example:
<html> <body> <?php Function Name() { echo "Ben John"; } Name(); ?> </body> </html>

PHP Functions - Adding parameters

A parameter is just like a variable. The parameters are specified inside the parentheses.

Functions can also be used to return values. Example: <html> <body> <?php function add($x,$y) { $total = $x + $y; return $total; } echo "1 + 16 = " . add(1,16); ?> </body> </html>

Syntax: <?php function function_name(param_1, ... , param_n) { statement_1; statement_2; ... statement_m; return return_value; } ?>

Control Structure

Control structures are the building blocks of any programming language. PHP provides all the control structures that you may have encountered anywhere. The syntax is the same as C or Perl. Making computers think has always been the goal of the computer architect and the programmer. Using control structures computers can make simple decisions and when programmed cleverly they can do some complex things.

Conditional Statements
The If...Else Statement Syntax
1.

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

If more than one line should be executed if a condition is true/false, the lines should be enclosed within curly braces:
<?php $d=date("D"); if ($d=="Fri") { echo "Hello!<br />"; echo "Have a nice weekend!"; echo "See you on Monday!";

<?php
$d=date("D"); if ($d=="Fri") echo "Have a nice weekend!";

Conditional Statements
<html><head> <title>good ......</title> </head> If you want to execute some <body> code if one of several <?php conditions is true use the $hour = date("H"); elseif statement if ($hour <= 11) { echo "good morning my friend"; } Syntax elseif ($hour > 11 && $hour < 18) { if (condition) code to be echo "good afternoon my friend"; } executed if condition is else { echo "good evening my true; friend"; } elseif (condition) code to ?> be executed if condition </body></html>

2. The ElseIf Statement

is true;

PHP Switch Statement


If you want to select one of many blocks of code to be executed, use the Switch statement. The switch statement is used to avoid long blocks of if..elseif..else code. Syntax switch (expression) { case label1: code to be executed if expression = label1; break; case label2: code to be executed if expression = label2; break; default: code to be executed if expression is different from both

switch ($textcolor) { case "black": echo "I'm black"; break; case "blue": echo "I'm blue"; break; case "red": echo "I'm red"; break; default: // It must be something else echo "too bad!!, I'm something else"; }

PHP Looping

Looping statements in PHP are used to execute the same block of code a specified number of times. In PHP we have the following looping statements:

while - loops through a block of code if and as long as a specified condition is true do...while - loops through a block of code once, and then repeats the loop as long as a special condition is true for - loops through a block of code a specified number of times foreach - loops through a block of code for each

The while Statement


Syntax

while (condition)
{ // statements }

Example <html> <head> <title>Let us count !!!</title></head> <body> <?php $limit = 10; echo "<h2> Let us count from 1 to $limit </h2><br />"; $count = 1; while ($count <= $limit) { echo "counting $count of $limit <br>"; $count++; } ?>

The do...while Statement

The do...while statement will execute a block of code at least once it then will repeat the loop as long as a condition is true.

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

Example <html> <body> <?php $i=0; do { $i++; echo "The number is " . $i . "<br />"; } while ($i<5); ?> </body> </html>

The for Statement

It is used when you know how many times you want to execute a statement or a list of statements.

Example <html> <body> <?php for ($i=1; $i<=5; $i++) { echo "Hello World!<br />"; } ?> </body> </html>

Syntax for (init; cond; incr) { code to be executed; } Parameters:

init: Is mostly used to set a counter, but can be any code to be executed once at the beginning of the loop statement. cond: Is evaluated at beginning of each loop iteration. If the condition evaluates to TRUE, the loop continues and the code executes. If it evaluates to FALSE, the execution of the loop ends. incr: Is mostly used to increment a

The foreach Statement

The foreach statement is used to loop through arrays. For every loop, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop, you'll be looking at the next element.

Syntax foreach (array as value) { code to be executed; }

Example <html> <body> <?php $arr=array("one", "two", "three"); foreach ($arr as $value) { echo "Value: " . $value . "<br />"; } ?> </body> </html>

PHP Arrays

An array can store one or more values in a single variable name. There are three different kind of arrays:
Numeric

array - An array with a numeric ID key Associative array - An array where each ID key is associated with a value Multidimensional array - An array containing one or more arrays

Numeric Array

A numeric array stores each element with a numeric ID key. There are different ways to create a numeric array:

Example 1 In this example the ID key is automatically assigned: $names = array("Peter","Quagmire","Joe"); Example 2 In this example we assign the ID key manually: $names[0] = "Peter"; $names[1] = "Quagmire"; $names[2] = "Joe";

Example 3: <?php $names[0] = "Peter"; $names[1] = "Quagmire"; $names[2] = "Joe"; echo $names[1] . " and " . $names[2] . " are ". $names[0] . "'s neighbors"; ?>

Associative Arrays

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. There are two ways of creating Associative Array:

Example 1 $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34); Example 2 $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34";

Example 3: <?php $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; echo "Peter is " . $ages['Peter'] . " years old."; ?>

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 2: 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 1 with automatically assigned ID keys:

$families = array ( "Griffin"=>array


( "Peter", "Lois", "Megan" ),

"Quagmire"=>array
( "Glenn" ),

displaying a single value from the array above: echo "Is " . $families['Griffin'][2] . " a part of the Griffin family?";

"Brown"=>array
( "Cleveland", "Loretta", "Junior"

CakePHP

Latest Platform for PHP Bases on MVC Fast Development Easy Development In Built Function

Das könnte Ihnen auch gefallen