Вы находитесь на странице: 1из 8

Chapter 4: Basics of PHP

4.1

What is php?

PHP, usually installed as a module inside the web server, is a popular server side scripting language in which
applications are written to communicate with MySQL (or other database systems) on the back end and browsers on the
front end. Ironically, the acronym's significance has evolved along with the web evolution, from Personal Home Page to
Professional Home Page to its current recursive definition Hypertext Preprocessor.
When a browser calls a PHP document, the Server reads the PHP document, runs the PHP code and returns the resulting
HTML code to the browser. The PHP script is executed on the server, and the plain HTML result is sent back to the
browser.
PHP is available on millions of web domains and powers famous sites such as Facebook, Yahoo!, YouTube, and
Wikipedia
4.2

Features of php

-PHP supports cookies and sessions


-PHP supports many databases (MySQL, Oracle, Sybase, etc.).
-PHP files can contain text, image, HTML tags and scripts
-PHP files are returned to the browser as plain HTML
-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
4.3
Setting up php with apache When we install Wamp server, all the required software to run php, such as,
Apache, PHP and MySQL are installed in Windows OS.
4.4

Basic php syntax

4.4.1 Php comments


<html>
<body>
<?php
//This is a comment
/*
This is
a comment
block
*/
echo "Comments are ignored";
?>
</body>
</html>
4.4.2 Predefined and user variables
Predefined variables: PHP provides a large number of predefined variables. The following variables are predefined in
php . They are called super global variables. They are always available in all scopes.
1

User defined variables: Rules for defining user defined PHP variables are,
Variables in PHP starts with a $ sign, followed by the name of the variable
The variable name must begin with a letter or the underscore character
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
A variable name should not contain spaces
Variable names are case sensitive (y and Y are two different variables)
In PHP, a variable does not need to be declared before adding a value to it.
PHP automatically converts the variable to the correct data type, depending on its value.
4.4.3 Variable types in php: The basic data types in PHP are

4.5

Retrieve data from html forms

User input should be validated on the browser whenever possible (by client scripts). Browser validation is faster and
reduces the server load.
You should consider server validation if the user input will be inserted into a database. A good way to validate a 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. This makes it easier to discover the error.
home.php
<form method="POST" action="home.php">
<input type="hidden" name= "posted" value="true">
Please enter your name:
<input type="text" name="fullname">
<input type="submit" value="Send">
</form>
<?php
if(isset($_POST['posted']))
echo "Hello ".$_POST['fullname'];
2

?>
1.php
<?php
echo '<a href="2.php?a=10&b=20">Click to goto page 2</a>';
?>
2.php
<?php
echo "a=$_GET[a]<br>";
echo "b=$_GET[b]";
?>
4.6

Displaying errors: Wampserver-PHP-PHP Settings-Check or Uncheck to display or hide errors.

4.7

Using numbers and strings in php

<?php
echo
"Hello
World";
?>
<?php
$name = "Anand"; echo "Hello, $name";
?>
<?php
$name = 'Anand'; echo 'Hello, $name';
?>
<?php
$weight=100; echo 'The total weight is ' . $weight . 'kg';
?>
4.8 Control structures: PHP supports control structures such as if, if-else, if-elseif-elseif--else, switch statements.
<?php
$a=5;$b=3;
if ($a > $b) echo "a is bigger than b"; ?>
<?php
$a=3;$b=5;
if ($a > $b) { echo "a is bigger than b";}
else { echo "a is NOT bigger than b";}
?>
<?php
$a=3;$b=5;
if ($a > $b) { echo "a is bigger than b";}
elseif ($a == $b) { echo "a is equal to b";}
else { echo "a is smaller than b";}
?>
<?php
$i=5;
switch ($i) {
case 0: echo "i equals 0";
3

case 1: echo "i equals 1";


case 2: echo "i equals 2";
default:echo "i is not equal to 0,1,or 2";
}
?>
4.9

Conditional and loop statements:

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
<?php
$a=array("Red","Blue","Green","Yellow");
$i=0;
while($i<count($a))
{echo "<br>".$a[$i];++$i;}
?>
<?php
$a=array("Red","Blue","Green","Yellow");
$i=0;
do {echo "<br>".$a[$i];++$i;} while($i<count($a));
?>
<?php
$a=array("Red","Blue","Green","Yellow");
for($i=0;$i<count($a);++$i)
echo "<br>".$a[$i];
?>
<?php
$a=array("Red","Blue","Green","Yellow");
foreach($a as $v)
echo "<br>".$v;
?>
<?php
$b=2.55;
$a=array("Red",12,true,3.44,$b);
foreach($a as $v) //see note below
echo "<br>".$v;
?>
<?php
$a["Lisa"] = "28";
$a["Jack"] = "16";
$a["Ryan"] = "35";
$a["Rachel"] = "46";
$a["Grace"] = "34";
foreach( $a as $k => $v) //see note below
4

{echo "Name: $k, Age: $v <br />";}


?>
Note: The statement foreach($a as $k=>$v) should be read as For each $a as $k of $v. It means, f or each
element of the associative array $a, I want to refer to the key as $k and the value as $v.
Similarly the statement foreach($a as $v) should be read as For each $a as $v. It means, for each element of the
array $a, I want to refer it as $v.
4.10

Introducing References

References:
References in PHP are a means to access the same variable content by different names. They are not like C pointers; for
instance, you cannot perform pointer arithmetic using them, they are not actual memory addresses.
There are three basic operations performed using references: assigning by reference, passing by reference, and returning
by reference.
By default, variables are always assigned by value. That is to say, when you assign an expression to a variable, the
entire value of the original expression is copied into the destination variable. This means, for instance, that after
assigning one variable's value to another, changing one of those variables will have no effect on the other.
PHP also offers another way to assign values to variables: assign by reference. This means that the new variable simply
references (in other words, "becomes an alias for" or "points to") the original variable. Changes to the new variable
affect the original, and vice versa.
To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the
source variable). For instance, the following code snippet outputs 'My name is Bob' twice:
<?php
$foo = 'Bob';
// Assign the value 'Bob' to $foo
$bar = &$foo;
// Reference $foo via $bar.
$bar = "My name is $bar"; // Alter $bar...
echo $bar;
echo $foo;
// $foo is altered too.
?>

My name is Bob
My name is Bob

When you unset the reference, you just break the binding between variable name and variable content. This does not
mean that variable content will be destroyed. For example, the below code, won't unset $b, just $a.
<?php
$a = 1;
$b =& $a;
echo "a=".$a."<br>"."b=".$b."<br>";
unset($a);
echo "a=".$a."<br>"."b=".$b."<br>";
?>
4.11
References and arrays
In PHP, there are three kinds of arrays:
Numeric array - An array with a numeric index
5

Multidimensional array - An array containing one or more arrays


Associative array - An array where each ID key is associated with a value
<?php
//Numeric Array
$colors=array("Red","Blue","Green","Yellow");
$fruits[0]="Apple";
$fruits[1]="Mango";
$fruits[2]="Grape";
echo "<br>".$colors[1];
echo "<br>".$fruits[1];
?>
<?php
//Multidimensional Array
$items['books'][0]="book0";
$items['books'][1]="book1";
$items['bags'][0]="bag0";
$items['pens'][0]="pen0";
$items['pens'][1]="pen1";
$items['pens'][2]="pen2";
echo $items['pens'][1];
?>
<?php
//Associative Array
$ages = array('Peter'=>32, 'Anand'=>42, 'Ram'=>34);
echo "<br>".$ages['Anand'];
?>
References are applicable to arrays also.
<?php
$a=array("zero","one","two");
$b=$a; //array $a is copied into array $b
$b[3]="three";
print_r($a);
echo"<br>";
print_r($b);
?>
<?php
$a=array("zero","one","two");
$b=&$a; //both $a,$b represent same array
$b[3]="three";
print_r($a);
echo"<br>";
print_r($b);
?>

4.12

Functions
6

<?php
// default parameter
function add_tax_rate($amount, $rate=10)
{ $total = $amount * (1 + ($rate / 100));
return($total); }
echo add_tax_rate(10);
echo "<br>".add_tax_rate(10, 9);
?>
<?php
// call by value
function increment($value, $amount = 1)
{$value = $value +$amount;}
$a = 10; echo $a.'<br />';
increment($a); echo $a.'<br />';
?>
4.12.1 Passing arguments by Reference (call by reference)
<?php
// call by reference
function increment(&$value, $amount = 1) {
$value = $value +$amount;
}
$a = 10;
echo $a.'<br />';
increment($a);
echo $a.'<br />';
?>
4.12.2 Functions : returning Reference
When you use a function to return a reference, you need follow these rules:

To declare a function that returns a reference, the function name must be prefixed with '&' in the function
definition statement.

If a function is declared to return a reference, it should use the 'return' statement to return a variable.

To call a function that returns a reference, the function name must be prefixed with '&' in the function call
operation.

The returning reference from a function should be assigned to another variable.


<?php
//using a function to return a reference
function &f($a) {$a+=10;return($a);}
7

$a=5;
$b=&f($a);
echo $b;
?>

***

Вам также может понравиться