You are on page 1of 50

1 Chapter 5- Basics of PHP

Outline
2

 Prerequisites for PHP


 What is PHP?
 Structure of PHP
 PHP functions
 Decision and repetition statements
 Accessing user inputs
 References and arrays
 Database manipulation with PhP
Prerequisites for PHP
3

 You can work on local machine


 Set up development server
 Some of them are:
 WAMP – Windows Apache MySQL and PHP
 XAMP is best for Windows flavor
 MAMP – Mac Apache MySQL and PHP
 LAMP – Linux Apache MySQL and PHP
 They come in the form of package
 Install and configure them – default is already done
Prerequisites for PHP
4

 You can work on local machine


 Once XAMP is installed, open xampp control panel
and start services
 Write your PHP code and store it in
C:/xampp/htdocs folder
 Open a browser and type
localhost/foldername/file.php to see result on
browser.
Prerequisites for PHP
5

 Working Remotely
 Web server already configured with PHP and
MySQL is needed
 High speed connection is needed
 Use Telnet or SSH to create databases and set
permissions from command line
 Need to have software like PuTTY for Telnet/SSH
access on windows PC , Mac has already SSH
 Use FTP softwares like FireFTP,FileZilla for file
transfer on webservers
Prerequisites for PHP
6

 Program Editors
 Plain-text editors
 Notepad
 For Highlighted code
 Notepad ++
 Editra
 IDE
 NetBeans
 phpDesigner
What is PHP?
7

 PHP stands for "PHP Hypertext Preprocessor"


 Server-side scripting language
 Used to make web pages dynamic:
 provide different content depending on context
 interface with other services: database, e-mail, etc.
 authenticate users
 process form information
 Language used to generate dynamic content from
the server every time client sends request
What is PHP?
8

 PHP documents end with extension .php


 Browser sends PHP codes to PHP processor
 Some webservers force HTML and CSS codes to
be parsed by the PHP processor to hide that they
are using php
 PHP starts with <?php
All php code should go here
 PHP ends with ?>
PHP syntax template
9

HTML content
<?php
PHP code
?>
HTML content
<?php
PHP code
?>
HTML content ... PHP

 Contents of a .php file between <?php and ?> are executed


as PHP code
 All other contents are output as pure HTML
 We can switch back and forth between HTML and PHP
"modes"
10 Structure of PHP
<?php
#………
//……...
/*……...
……*/
?>
Comments , Semicolons
11

 Single comments
 #
 //
 Multi line comment
 /* */
 All php commands should end with semicolon
 Variable declarations
 Formulas/expressions
 Statements etc.
Variables
12

$name = expression; PHP

$user_name = “kebedexxx";
$age = 16;
$drinking_age = $age + 5;
$this_class_rocks = TRUE; PHP

 names are case sensitive


 names always begin with $, on both declaration and
usage, and should be valid
 always implicitly declared by assignment (type is
not written)
 a loosely typed language (like JavaScript or
Python)
Console output: print
13

print "text";
PHP

print "Hello, World!\n";


print "Escape \"chars\" are the SAME as in Java!\n";
print "You can have
line breaks in a string.";
print 'A string can use "single-quotes". It\'s cool!';
PHP

Hello world! Escape "chars" are the SAME as in Java! You can have line
breaks in a string. A string can use "single-quotes". It's cool!
output
Hello World!
14

<?php
print "Hello, world!";
?> PHP

Hello world!
output
Echo vs print
15

Echo Print

 Pure php construct  Function like


 Faster in execution – construct
because it has no  Returns a value (i.e 1)
return value  Used in more complex
 Cannot be used in part expression
of more complex  E.g: $b=6;
expression $b>5?print”true”:print”false”;

Neither requires parenthesis


Arithmetic operators
16

 + - * / % . ++ --
 = += -= *= /= %= .=
 many operators auto-convert types: 5 + "7" is 12
Logical Operators
17
Precedence (High to low)
18
Examples
19

$a = 7 / 2; # float: 3.5
$b = (int) $a; # int: 3
$c = round($a); # float: 4.0
$d = "123"; # string: "123"
$e = (int) $d; # int: 123 PHP

 int for integers and float for reals


 division between two int values can produce a float
String Type
20

$favorite_food = "Ethiopian";
print $favorite_food[5].”<br>”;
$favorite_food = $favorite_food . " Shiro";
print $favorite_food;
#output
P
Ethiopian Shiro
 zero-based PHP
indexing using bracket notation
 there is no char type; each letter is itself a String
 string concatenation operator is . (period), not +
 5 + "2 turtle doves" === 7
 5 . "2 turtle doves" === "52 turtle doves"
 can be specified with double quotes or single quotes
String Functions (cont.)
21

Name Java Equivalent


strlen length
strpos indexOf
substr substring
strtolower, strtoupper toLowerCase, toUpperCase
trim trim
explode, implode split, join
strcmp compareTo
String Functions Example
22

# index 01234567890
$name = "Abebe Bikila";
$length = strlen($name);
$cmp = strcmp($name, “Abebe Kitila");
$index = strpos($name, "e");
$first = substr($name, 6, 6);
$name = strtoupper($name);
print $length."<br>";#12
print $cmp."<br>";#-1
print $index."<br>";#2
print $first."<br>";#Bikila
print $name;#ABEBE BIKILA PHP
Interpreted Strings
23

$age = 16;
print "You are " . $age . " years old.\n";
print "You are $age years old.\n"; # You are 16 years old.
PHP

 strings inside " " are interpreted


 variables that appear inside them will have their values
inserted into the string
 strings inside ' ' are not interpreted:
print ' You are $age years old.\n '; # You are $age years
old. \n PHP
Interpreted Strings (cont.)
24

print "Today is your $ageth birthday.\n"; # $ageth not


found
print "Today is your {$age}th birthday.\n";
PHP

 if necessary to avoid ambiguity, can enclose


variable in {}
Boolean type
25

 Can hold a value either


 TRUE or
 FALSE
 FALSE is defined as NULL or nothing in php
$x=20>9;
echo $x; #outputs 1
$y=20<9;
echo $y; #outputs nothing echo
“[“.TRUE.”]”; #outputs [1]
echo “[.FALSE.”]”; #outputs []
PHP
26 Decision and repetition in PHP
<?php
for($i=0;$i<=10;$i++)
{
……..
}
?>
Decision & Repetition statements
27

 Php decision statements are similar with java


 If-else
 Nested if
 switch
 Php repetition statements are similar with java
 For
 While
 Do-while
if/else statement
28

if (condition) {
statements;
} elseif (condition) {
statements;
} else {
statements;
}
PHP

switch(expr){
case val1: statement1; break;
case val2: statement2; break;
case val3: statement3; break;
default: statement;
}
PHP
Example
29

if($bank_balance < 100)


{
$money = 1000;
$bank_balance += $money;
}
elseif($bank_balance > 200)
{
$savings += 100;
$bank_balance -= 100;
}
else
{
$savings += 50;
$bank_balance -= 50;
}
PHP
for loop (same as Java)
30

for (initialization; condition; update) {


statements;
}
PHP

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


print "$i squared is " . $i * $i . "<br>";
}
#output
0 squared is 0
1 squared is 1
2 squared is 4
3 squared is 9
. . .
9 squared is 81
PHP
while loop (same as Java)
31

while (condition) {
statements;
} PHP

do {
statements;
} while (condition);
PHP
32 PHP Arrays
<?php
$a=array(………………..);
$b=array(…array(…..) );
foreach(elem in $a)
{
…….
} ?>
PHP arrays
33

 Arrays are an example of what has made PHP so


popular
 They remove the tedium of writing code to deal
with complicated data structures
 They also provide numerous ways to access data
while remaining amazingly fast
 Can be
 Numerically indexed
 Alphanumeric indexed (Associative arrays)
Basic Access
34

 Use index to access array elements


 Use built-in functions:
 To sort
 To add
 To remove
 To walk through array elements
 Place one or more array inside another to create a
multidimensional array.
Numerically indexed arrays
35

 The following creates an array:


<?php
$paper[]=“Copier”;
$paper[]=“Inkjet”;
$paper[]=“Laser”;
$paper[]=“Photo”;
print_r($paper);//prints the array
?> PHP

 Produces the following:


Array([0]=>Copier [1]=>Inkjet [2]=>Laser [3]=>Photo)
 print_r used to print contents of variable , array or
object.
…cont’d…
36

 Access the elements as follows


<?php
$paper[]=“Copier”;
$paper[]=“Inkjet”;
$paper[]=“Laser”;
$paper[]=“Photo”;
for($i=0;$i<4;$i++){
echo"$i:$paper[$i]";
echo"<br>";
}?> PHP

 Produces the following result:


0:Copier
1:Inkjet
2:Laser
3:Photo output
Associative arrays
37

 Remembering which index refers to which element


is a headache in numeric indexed arrays.
 This type of array avoids remembering of index
numbers by providing alphanumeric indexes for
elements
 Uses names as keys or indexes to refer to an
element or value.
 $_GET , $_POST are built-in associative arrays
used to store user inputs
Example Index/
Key
Value
38

 The following creates associative array of previous


example
<?php
$paper['copier']="Copier & Multipurpose";
$paper['inkjet']="Inkjet printer";
$paper['laser']="Laser Printer";
$paper['photo']="Photograpic paper";
echo $paper['copier'];
?> PHP

 Produces the following output


Copier & Multipurpose
Assignment using array keyword
39

 Both numeric and associative arrays can be


assigned using this method
<?php
$p1 = array("Copier", "Inkjet", "Laser", "Photo");
echo "p1 element: " . $p1[2] . "<br>";
$p2 = array('copier' => "Copier & Multipurpose",
'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer",
'photo' => "Photographic Paper");
echo "p2 element: " . $p2['inkjet'] . "<br>";
?> PHP

 Outputs the following


p1 element : Inkjet
p2 element : Inkjet printer output
…cont’d…
40

 Iterate over array elements by using foreach loop.


 Format:
foreach($arrayVariable as $newVariable) {
//statements
}
<?php
$p1 = array("Copier", "Inkjet", "Laser", "Photo");
foreach($p1 as $elem)
{
echo $elem."<br>";
}
?> PHP
…cont’d…
41

 Foreach loop in associative array:


<?php
$paper = array('copier' => "Copier & Multipurpose",
'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer",
'photo' => "Photographic Paper");
foreach($paper as $item => $description)
echo "$item: $description<br>";
?> PHP
 Displays the following output
copier: Copier & Multipurpose
inkjet: Inkjet Printer
laser: Laser Printer
photo: Photographic Paper output
Array functions
42

Function Name Use Example


is_array() Checks if variable is array is_array($p1);
count() Counts elements of array count($p1);
sort() Sorts elements of array sort($p1,SORT_STRING);
rsort() Sorts elements of array in rsort($p1);
reverse order
shuffle() Puts elements of array in shuffle($p1);
random order
explode() Splits elements of an array using explode(‘ ‘, “This is array”);
characters
extract() Extracts key value pairs from extract($_GET,EXTR_PREFIX_
$_GET ,$_POST etc. ALL, ‘fromGet’);
compact() Opposite of extract() compact(‘user’,’pass’);
end() Moves the array to last element end($p1);
PHP Superglobals
43
Array Description
parameters passed to any type of
$_REQUEST
request
parameters passed to GET and POST
$_GET, $_POST
requests
$_SERVER, $_ENV information about the web server
$_FILES files uploaded with the web request
"cookies" used to identify the user
$_SESSION, $_COOKIE
(seen later)

 PHP superglobal arrays contain information about


the current request, server, etc.
 These are special kinds of arrays called associative
arrays.
Example
44

<form action=“formProcess.php” method=“POST”>


Name:<input type=“text” name=“name” size=30><br>
Birthday:<input type=“text” name=“bday” size=10><br>
<input type=“submit” name=“submit” value=“Submit Query”>
</form>
HTML

formProcess.php
<html>
<body>
Welcome <?php $_POST[“name”];?><br>
Your birthday is:<?php $_POST[“bday”];?>
</body>
</html>
PHP
45 Php Functions
<?php
function function_name(par1,par2,…, parN)
{
-------
}
?>
Functions
46

function name(parameterName, ..., parameterName) {


statements;
} PHP

function quadratic($a, $b, $c)


{
return -$b + sqrt($b * $b - 4 * $a * $c) / (2 * $a);
} PHP

 parameter types and return types are not written


 a function with no return statements implicitly returns NULL
Including files:
47
include/require
include("header.php"); #or
require(“footer.php");
PHP
 inserts the entire contents of the given file into the
PHP script's output page
 encourages modularity
 useful for defining reused functions needed by
multiple pages
 require is better for its error reporting incase the
file is not found
 Also use include_once() or require_once()
MYSQL functions
MYSQL_ASSOC
MYSQL_NUM

48

 PHP enables database integration and processing of


data stored in database table:
 The built in functions are as follows:
 mysql_connect(host,username,password) connects to
db
 mysql_close() closes connection
 mysql_query(sql,con) executes any sql query
 mysql_select_db(db,con) chooses a database
 mysql_fetch_array(sql,type) retrieves table data
 mysql_fetch_assoc(sql) retrieves database table data
Example
49

<?php
$host=‘localhost:3306’;
$user=‘root’;
$pass=‘’;
$con=mysql_connect($host,$user,$pass); #create con
$sql=‘create Database A’;
$db=mysql_query($sql,$con); #creates db A
if(!$db)
die(‘couldn’t create database’);
else
echo ‘Database created successfully’;
?>
PHP
…continued
50

<?php
mysql_select_db(‘A’,$con); #selects db A
$sql2=‘select * from XXX’;
$exe=mysql_query($sql2,$con);
#retrieval of data from table xxx
while($r=mysql_fetch_array($exe,MYSQL_ASSOC))
{
echo “A:{$r[‘A’]}<br>”.
“B:{$r[‘B’]}<br>”.
“<br>”;
}
mysql_close($con); //closes con
?> PHP

You might also like