0% found this document useful (0 votes)
6 views

Web06_PHPBasic

Uploaded by

Anh Phi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Web06_PHPBasic

Uploaded by

Anh Phi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 130

WEB DESIGN

HienLTH – KhietLTN Web Design 1


PHP Basic

MSc. Luong Tran Ngoc Khiet

HienLTH – KhietLTN Web Design 2


Content

1. Introducing PHP
2. PHP Operation & Installation
3. Syntax
4. Out
5. Operator
6. Chain
7. Arrays
8. Controller structure
9. Jaw
HienLTH – KhietLTN Web Design 3
1. Introduction PHP – History
• PHP : Rasmus Lerdorf in 1994 (developed to generate login forms
using Unix HTTP protocol)
• PHP 2 (1995) Switch to the script language processing on the server.
Database support, File Upload, variable declaration, array, recursive
function, conditional sentence, expression, ...
• PHP 3 (1998) : Supports ODBC, multi-OS, email protocol (SNMP,
IMAP), PHP code parser (parser) by Zeev Suraski and Andi Gutmans
• PHP 4 (2000) : Become a standalone component for webserver. Parse
changed its name to Zend Engine. Additional security features for PHP
• PHP 5 (2005) : Add Zend Engine II to support OO, XML, SOAP
programming for Web Services, SQLite
• Phiên bản mới nhất của PHP là version PHP 7.3 (www.php.net –
12.02.2019)

HienLTH – KhietLTN Web Design 4


1. Introduction PHP – History

HienLTH – KhietLTN Web Design 5


1. Introduction PHP –
what is PHP?
• PHP was developed from scripting language for
the purpose of building personal Web pages
(Personal Home Page). It was later developed into
a complete language and is preferred worldwide
for developing Web applications.
• PHP is an interpreted language.
• Server-side script language, similar to ASP, JSP,
... executed on the Server side.
• PHP file has the extension .php
• The syntax is similar to C & Perl

HienLTH – KhietLTN Web Design 6


1. Introduction to PHP -
Advantages

(Multi - Platform)
• Web Servers: Apache, Microsoft IIS, Caudium, Netscape Enterprise
Server
• Hệ điều hành: UNIX (HP-UX, OpenBSD, Solaris, Linux), Mac OSX,
Windows NT/98/2000/XP/2003/vista
• Hệ QTCSDL: Adabas D, dBase, Empress, FilePro (read-only),
Hyperwave, IBM DB2, Informix, Ingres, InterBase, FrontBase, mSQL,
Direct MS-SQL, MySQL, ODBC, Oracle (OCI7 and OCI8), Ovrimos,
PostgreSQL, SQLite, Solid, Sybase, Velocis, Unix dbm

HienLTH – KhietLTN Web Design 7


1. Introduction to PHP -
Advantages
PHP is widely used in web development
environment
Source: http://php.net/usage.php
http://w3techs.com/technologies/overview/programming_language/all

HienLTH – KhietLTN Web Design 8


Advantages and
disadvantages of PHP?
Đánh giá JSP PHP .Net
ƯU ĐIỂM ✓Open source ✓Open source  Open source
✓Clearly code  Mix code ✓Clearly code
(HTML,JSP,..) (HTML,PHP) (HTML,.Net,..)
✓The best DBMS ✓The best DBMS ✓The best DBMS
support: Oracle support : MySQL support : SQL Server

✓ Code same as: C


✓ Config: easy
✓ Community
support: good

KHUYẾT ✓ Run: slow ✓ Support: poor


ĐIỂM
✓ Support: poor ✓ IDE: poor
✓ Config: complex
HienLTH – KhietLTN Web Design 9
Some websites use PHP

HienLTH – KhietLTN Web Design 10


2. Web Server Operation

CƠ CHẾ HOẠT ĐỘNG

HienLTH – KhietLTN Web Design 11


2. Web Server Operation
• Apache and IIS are built to respond to requests for HTML
files
• Don't understand how to execute PHP code on the server
side
• Apache uses modules to "understand" how to execute
scripts written in PHP
• IIS uses the ISAPI script - Internet Server Application
Programming Interface - to "understand" PHP and ASP
commands
• Additionally, both Apache and IIS support multiple service
modules for deploying web applications efficiently

HienLTH – KhietLTN Web Design 12


2. Web Server Operation
<html>
<head>
<title>PHP Test</title> hello.php
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
</body>
</html>
<html>
<head>
<title>PHP Test</title> output
</head>
<body>
<p>Hello World</p>
</body>
</html>
HienLTH – KhietLTN Web Design 13
2. Web Server Operation

HienLTH – KhietLTN Web Design 14


2. Web Server Operation

Sử dụng phương thức echo "Nội dung" để xuất thông


tin lên trình duyệt.
HienLTH – KhietLTN Web Design 15
2. Requirements for
installation
• Download Apache Server
Download Apache for free here:
http://httpd.apache.org/download.cgi
• Download PHP
Download PHP for free here:
http://www.php.net/downloads.php
• Download MySQL Database
Download MySQL for free here:
http://www.mysql.com/downloads/index.html

HienLTH – KhietLTN Web Design 16


2. Requirements for
installation
PHƯƠNG ÁN 1
http://www.apachefriends.org/en/xampp.html

PHƯƠNG ÁN 2

http://www.wampserver.com/en/

PHƯƠNG ÁN 3 Cấu hình manual

HienLTH – KhietLTN Web Design 17


2. Requirements for
installation
Sử dụng giải pháp trọn gói (All in One):

• LAMP – Linux

• WAMP – Windows

• XAMPP – Windows/Linux

HienLTH – KhietLTN Web Design 18


XAMPP - Tutorial

HienLTH – KhietLTN Web Design 19


XAMPP - Tutorial
• Chỉnh port cho Server

HienLTH – KhietLTN Web Design 20


XAMPP - Tutorial
• Chỉnh port cho Server

HienLTH – KhietLTN Web Design 21


phpMyAdmin

HienLTH – KhietLTN Web Design 22


Database:

phpMyAdmin: GUI interface to MySQL


MySQL Workbench: Database Visioning/Mgmt

HienLTH – KhietLTN Web Design 23


3. Syntax

• Speech :
• Use <? Php…?> To highlight PHP commands
• The php statements are separated by ‘;’
• Irrespective space, tab or newline character.
• For example:
<?php echo “Hello”; echo “World!”; ?>
<?php
echo “Hello” ;
echo “World!”;
?>
HienLTH – KhietLTN Web Design 24
3. Syntax (tt) – Note

• PHP's Note is similar to that of C ++ and Perl


• There are 3 types of notes:
– Use ‘//’ for notes
– Use ‘#’ for notes
– Use /* … */ for notes
• For example:
<?php
print “chào mọi nguời.”; //print dùng để xuất chuỗi
?>
<?php print $bien; ?> #tương tự như <?=$bien; ?>

HienLTH – KhietLTN Web Design 25


3. Syntax (tt) – datatypes
• boolean
• integer
• double
• string
• array
• object

A variable in PHP can store any data type

HienLTH – KhietLTN Web Design 26


Number_format output format
<?php
$length = 21000.1;
$width = 300.53;
$area = $length * $width;
$text = “The area is: ”;
printf($text.“%0.2f <br />”, $area);
echo number_format($area, 2);
?>

HienLTH – KhietLTN Web Design 27


3. Datatypes
• Chuyển đổi kiểu dữ liệu
– Cách 1 (automatic)
$var = “100” + 15;
$var = “100” + 15.0;
$var = 39. “ Steps”;//Chú ý
– Cách 2 (datatype) $var
– Cách 3 settype($var, “datatype”)
• EG:

HienLTH – KhietLTN Web Design 28


3. Datatypes

• Check the data type


gettype is_string isset
is_int is_array unset
is_double is_object empty
is_numeric

• For example
$var = “test”;
if (isset($var))
echo “Variable is Set”;
if (empty($var))
echo “Variable is Empty”;

HienLTH – KhietLTN Web Design 29


3. Datatypes

• Some functions that process numbers


abs pow decbin srand(seed)
ceil sqrt bindec rand
floor log dechex rand(min, max)
round log10 hexdec …
• For example:
// Phát sinh một “mầm” ngẫu nhiên
Tra hướng dẫn
$seed = (float) microtime()*100000000;
// Khởi tạo bộ phát sinh số ngẫu nhiên trong PHP Manual
srand($seed);
// In số ngẫu nhiên
print rand(); // Giá trị ngẫu nhiên từ 0 đến getmaxrand( )
print rand(1, 6); // Giá trị ngẫu nhiên từ 1 đến 6

HienLTH – KhietLTN Web Design 30


3. Datatypes
<?php
$n = 43951789; Hàm printf
$u = -43951789;
$c = 65; // ASCII 65 is 'A' %b = '10100111101010011010101101'
%c = 'A'
printf("%%b = '%b'\n", $n); %d = '43951789'
printf("%%c = '%c'\n", $c); %e = '4.39518e+7'
printf("%%d = '%d'\n", $n);
%u = '43951789'
printf("%%e = '%e'\n", $n);
printf("%%u = '%u'\n", $n); %u = '4251015507'
printf("%%u = '%u'\n", $u); %f = '43951789.000000'
printf("%%f = '%f'\n", $n); %o = '247523255'
printf("%%o = '%o'\n", $n); %s = '43951789'
printf("%%s = '%s'\n", $n);
%x = '29ea6ad'
printf("%%x = '%x'\n", $n);
printf("%%X = '%X'\n", $n); %X = '29EA6AD'
printf("%%+d = '%+d'\n", $n); %+d = '+43951789'
printf("%%+d = '%+d'\n", $u); %+d = '-43951789'
?>
HienLTH – KhietLTN Web Design 31
3. Datatypes
<?php
$input = "Alien";
echo str_pad($input, 10); // produces "Alien "
echo str_pad($input, 10, "-=", STR_PAD_LEFT); // produces "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH); // produces "__Alien___"
echo str_pad($input, 6 , "___"); // produces "Alien_"
?>

Hàm str_pad

STR_PAD_RIGHT : Thêm vào bên phải (mặc định)


STR_PAD_LEFT : Thêm vào bên trái
STR_PAD_BOTH : Thêm cả hai phía
HienLTH – KhietLTN Web Design 32
4. Variables

• Syntax: $ten_bien = value;


• No data type declaration
• Variables are initialized automatically when assigning
values for the first time
• Variable name
– Include characters (A..Z, a..z), digital (0..9), _
– Must not start with a digit (0..9)
– Distinguish uppercase - lowercase
• For example:
– Correct syntax: $hoten, $_pass
– Incorrect syntax: $2host

HienLTH – KhietLTN Web Design 33


4. Variables– constants
• Variable variables
– Allows to change variable name
– For example
<?php
$varname=“Bien_moi”;
$$varname= “xyz”; //$Bien_moi= “xyz”
?>
• Hằng số - Constants
<?php
define("MY_CONST", 10);
echo MY_CONST;
?>

HienLTH – KhietLTN Web Design 34


5. Operator
Type Operator Note
new .

. [] ()

Toán học + - * / % ++ --

So sánh < > <= >= != == === !==

Luận lý && || ?: ,

Xử lý bit ! ~ << >> >>>


AND OR XOR
Gán = += -= *= /= %=
>>= <<= &= |= ^= .=
Ép kiểu (kiểu dữ liệu) (int) (double) (string)…
HienLTH – KhietLTN Web Design 35
5. Operator
Ex Name Result
$a == $b Equal TRUE if $a is equal to $b.

$a === $b Identical TRUE if $a is equal to $b, and they are of the same type. (PHP 4)

$a != $b Not equal TRUE if $a is not equal to $b.

$a <> $b Not equal TRUE if $a is not equal to $b.

$a !== $b Not identical TRUE if $a is not equal to $b, or they are not of the same type. (PHP 4)

$a < $b Less than TRUE if $a is strictly less than $b.

$a > $b Greater than TRUE if $a is strictly greater than $b.

$a <= $b Less than or equal to TRUE if $a is less than or equal to $b.

36
$a >= $b Greater than or equal to TRUE if $a is greater than or equal to $b.
HienLTH – KhietLTN Web Design 36
6. String

• String concatenation operator “.”


$str=“Hello “ . ”World!”; //$str = “Hello World!”;
• Distinguish single quotes, double quotes
$user = “Mr Bean”;
print ‘Hi $user’; // Hi $user
print “Hi $user”; // Hi Mr Bean
print “Hi”. $user; // ????
print “Hi”. “$user”; // ????

HienLTH – KhietLTN Web Design 37


6. String
• Delimited by single quotes ( ') or double ( ")
• The string enclosed in quotation marks is
replaced and the escape character is
processed. In single quotes are not.
• For example:
$a = “Hello”;
$b = “$a world”; //tương đương $b=“Hello
world”
$c = ‘$a world’; //$c=‘$a world’ (không
thay đổi)
HienLTH – KhietLTN Web Design 38
6. String

• To clarify the variables in the string, you


need to enclose the variable between the
curly braces { }
$a = “He”;
$b = “$allo”; //lỗi vì PHP hiểu là
$allo
$c = “{$a}llo”; //đúng ($c =
“Hello”)

HienLTH – KhietLTN Web Design 39


6. String

• Character Escape : \
– Use to write special characters in string
– EG:
Cần có chuỗi: Người ta nói “PHP rất tốt”
$a = “Người ta nói “PHP rất tốt””; //Sai
$a = “Người ta nói \“PHP rất tốt\””;
//Đúng
– Some characters must use an escape character : $, \, “
– Besides:
• \ n: Line break
• \ r: return to the beginning of the line
• \ t: tab
• ...
HienLTH – KhietLTN Web Design 40
6. String– document type
(heredoc)
– Allows writing 1 string on multiple lines
– No need to use the escape character:
– How to write:
$variable = <<<symbol
content on multiple lines
symbol;
– Note: Symbol must be written on the first
character of the line
– For example:
$a = <<<EOD
This is a multi-line string using the
'heredoc' document type syntax.
EOD;
HienLTH – KhietLTN Web Design 41
6. String– document type
(heredoc)
<?php
$str = <<<EOA
Example of string <br>
spanning multiple lines<br>
using heredoc syntax.<br>
EOA;//không được có khoảng trắng đầu dòng

echo($str);
$name = “mr bean";
$d = date("d/m/y");
$str = <<<EOQ
This is a lecture of $name.<br>
Ngay $d<br>
EOQ;
echo($str);
?>– KhietLTN
HienLTH Web Design 42
6. String – Handler function

• The basic handling


– strlen($string)
– substr($string, $position, $height)
– strtoupper ($string)
– strtolower ($string)
– Iconv (Source code, destination code,
$string)
– trim($string, ’ characters want to cut’)
– ltrim($string, characters want to cut’)
– rtrim($string, ’ characters want to cut’)
HienLTH – KhietLTN Web Design 43
6. String

• Search
– strpos($chuỗi, $chuỗi_con, $vị_trí_bắt đầu)
– strrpos ($chuỗi, $chuỗi_con, $vị_trí_bắt đầu)
• Compare
– strcmp($chuỗi_1, $chuỗi_2)
– strncmp($chuỗi_1, $chuỗi_2, $chiều_dài)
– strcasecmp($chuỗi_1, $chuỗi_2)
– strncasecmp($chuỗi_1, $chuỗi_2, $chiều_dài)
– strnatcmp($chuỗi_1, $chuỗi_2)
– strnatcasecmp($chuỗi_1, $chuỗi_2)
HienLTH – KhietLTN Web Design 44
6. String
<?php

$array = array('lastname', 'email', 'phone');


$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

?>
<?php
Xử lý chuỗi
// Example 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
// Example 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user,$pass,$uid,$gid,$gecos,$home,$shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *
?>

HienLTH – KhietLTN Web Design 45


7. Array
▪ Arrays in PHP can be declared in two ways:
➢ Enumerative Array
<?php
$colors = array('red', 'blue', 'green', 'yellow');
sort($colors);
foreach ($colors as $color)
{ Do you like blue?
echo "Do you like $color?<br>";Do you like green?
} Do you like red?
$num = count($colors); Do you like yellow?
We have 4 items
echo “We have $num items<br>”;
?>
The first element in the array has index index = 0
HienLTH – KhietLTN Web Design 46
7. Array

<?php
// PHP 5
foreach ($colors as &$color) {
$color = strtoupper($color);
}
unset($color); /* ensure that following writes to
$color will not modify the last array element */

// Workaround for older versions (phiên bản trước PHP 5)


foreach ($colors as $key => $color) { Array
$colors[$key] = strtoupper($color); (
} [0] => RED
[1] => BLUE
print_r($colors); [2] => GREEN
?> [3] => YELLOW
)

HienLTH – KhietLTN Web Design 47


7. Array
➢ Associative Array
<?php
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");

$c = $a + $b; // Union of $a and $b


echo "Union of \$a and \$b: \n";
var_dump($c);

$c = $b + $a; // Union of $b and $a


echo "Union of \$b and \$a: \n";
var_dump($c);
?>
Union of $a and $b: Union of $b and $a:
array(3) array(3)
{ {
["a"]=> string(5) "apple" ["a"]=> string(4) "pear"
["b"]=> string(6) "banana" ["b"]=> string(10) "strawberry"
["c"]=> string(6) "cherry" ["c"]=> string(6) "cherry"
} }
HienLTH – KhietLTN Web Design 48
7. Array
<?php
/* Suppose that $var_array is an array returned from
wddx_deserialize */
$size = "large";
$var_array = array("color" => "blue",
"size" => "medium",
"shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");
echo "$color, $size, $shape, $wddx_size\n";
?>

blue, large, sphere, medium

HienLTH – KhietLTN Web Design 49


7. Array
<?php
$info = array('coffee', 'brown', 'caffeine');

// Listing all the variables


list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";

// Listing some of them


list($drink, , $power) = $info;
echo "$drink has $power.\n";

// Or let's skip to only the third one


list( , , $power) = $info;
echo "I need $power!\n";

// list() doesn't work with strings


list($bar) = "abcde";
var_dump($bar); // NULL
?>
HienLTH – KhietLTN Web Design 50
7. Array – Handler function
• Sort
Theo giá trị
– sort($mảng) / asort($mảng) // tăng dần
– rsort($mảng) / arsort($mảng) // giảm dần
– natsort($mảng) / natcasesort($mảng)// tăng dần, dùng cho chuỗi
– usort($mảng, ”hàm_so_sánh”) // tự định nghĩa thứ tự
– uasort($mảng, ”hàm_so_sánh”) // tự định nghĩa thứ tự

Theo khóa
– ksort($mảng) // tăng dần
– krsort($mảng) // giảm dần
– uksort($mảng, ”hàm_so_sánh”) // tự định nghĩa thứ tự

HienLTH – KhietLTN Web Design 51


7. Array – Handler function
• Concatenates two arrays
array_merge($array1, $array2)
array_combine($array1, $array2)
array_intersect($array1, $array2)

• Search
array_search($value, $array)

HienLTH – KhietLTN Web Design 52


The problem involves an array

➢ one-dimensional array:
1. Build an array import / export function
2. Write a function to find the max, min element in the array
3. Sort array ascending, descending
4. Finds the element with the x value in the array
5. Updates the value for the element with the x value in the array
6. Remove the element with x value in the array
➢ two-dimensional array:
1. Build an array import / export function
2. Export elements on the primary diagonal and secondary
diagonal.
3. Arrange the array descending clockwise

HienLTH – KhietLTN Web Design 53


Break
HienLTH – KhietLTN Web Design 54
▪ Họ tên:
▪ Mã SV:
▪ Lớp:
▪ Khoá:
▪ Email:

01 02 … 19 20

55
HienLTH – KhietLTN Web Design 55
Question 1: Which of the following
PHP lines of code is not valid?
A. $_10
B. ${“MyVar”}
C. &$something
D. $10_somethings

HienLTH – KhietLTN Web Design 56


Question 2: What are the results of the following
script?
<?php
define("myvalue","10");
$myarray[10]= "Dog";
$myarray[] ="Human";
$myarray['myvalue'] = "Cat";
$myarray["Dog"]= "Cat"; print "The
value is:";
print $myarray[myvalue]."\n";
?>
A. The value is: Dog
B. The value is: Cat
C. The value is: Human
D. $10_somethings
HienLTH – KhietLTN Web Design 57
Question 3 : What are the results of the
following script?
<?php
$a = 10; $b = 20; $c = 4;
$d = 8;
$f = $c + $d * 2;
$g = $f % 20;
$h = $b - $a + $c + 2; print $h;
?>
A. 42
B. 16
C. 18
D. All wrong

HienLTH – KhietLTN Web Design 58


Question 4: Specifies the value to assign to the variables $ a, $ b, $ c so that
the script outputs the words "Hello, World!"?
<?php
$string= "Hello, World!";
$a =???; $b =???; $c =???;
if($a) {
if($b &&!$c){ echo "Goodbye Cruel World!";
} else if(!$b &&!$c) { echo "Nothing here"; }
} else { if(!$b) {
if(!$a && (!$b && $c)) {echo"Hello, World!";
} else { echo"GoodbyeWorld!"; }
} else { echo "Not quite."; }
}
?>
A. false, true, false
B. true, true , false
C. false, true, true
D. false, false, true

HienLTH – KhietLTN Web Design 59


Question 5: Said the results of the command segment?
<?php
$array = '0123456789ABCDEFG';
$s ='';
for ($i = 1; $i < 50; $i++) {
$s .=$array[rand(0,strlen ($array) - 1)];
}
echo $s;
?>
A. Output string with 49 random characters
B. Output string with 49 characters ‘G’
C. Output string with 50 random characters
D. Error because $ array is not an array.
HienLTH – KhietLTN Web Design 60
Question 6: Said the results of the command
segment?
<?php
$array = array ('1', '2'); foreach
($array as $k => $v) {
echo ($k+$v)." ";
}
?>
A. 1 2
B. 0 1
C. 1 3
D. All are wrong
HienLTH – KhietLTN Web Design 61
Question 7: Which function to reverse array
content?
<?php
$array = array ('a', 'b','c', 'd');
?>
➔ output: 'd', 'c','b', 'a'
A. rsort()
B. array_reverse()
C. Both a and b are correct
D. All are wrong

HienLTH – KhietLTN Web Design 62


Question 8: Which function to reverse
array content?
<?php
$array = array (0.1=>'a', 0.2=>'b');
echo count($array);
?>
A. 1
B. 2
C. 0
D. The statement has a wrong syntax

HienLTH – KhietLTN Web Design 63


Question 9: Said the results of the command segment?
<?php
$array = array (1, 2, 3, 5, 8, 13, 21);
$sum= 0;
for ($i= 0;$i < 3;$i++) {
$sum+=$array[$array[$i]];
}
echo $sum;
?>
A. NULL
B. 10
C. 19
D. Error command
HienLTH – KhietLTN Web Design 64
Question 10: Give command instead of key to
output string "php"?
<?php
$alpha = 'abcdefghijklmnopqrstuvwxyz';
$letters =array(15, 7, 15);
foreach($letters as $val) {
key
}
?>
A. echo chr($val);
B. echo substr($alpha, $val, 2);
C. echo $alpha{$val};
D. echo $alpha{$val+1};
HienLTH – KhietLTN Web Design 65
Question 11: Which statement is used
to concatenate 2 strings?
A. $s1 +$s2
B. "{$s1}{$s2}"
C. $s1.$s2
D. Both B and C are correct

HienLTH – KhietLTN Web Design 66


Question 12: String
$s = "[email protected]", Which
statement is used to extract the
substring "gmail.com"?
A. substr($s,strpos($s, "@"));
B. strstr($s,"@");
C. substr($s,strpos($s, "@")+1);
D. strrpos($s, "@");

HienLTH – KhietLTN Web Design 67


Question 13: Said the results of
the following statements?
echo 'Testing ' . 1+ 2 . '45';
A. Testing 1245
B. Testing 345
C. Testing 1+245
D. 245

HienLTH – KhietLTN Web Design 68


Question 14: Which of the following
statements returns true?
A. 'top'==0
B. 123 =='123'
C. '1top' =='1'
D. Both A and B are correct

HienLTH – KhietLTN Web Design 69


Question 15: said the results of the
command segment? <?php
function hello($who = "World")
{
echo "Hello $who ";
}
hello(hello());
?>
A. Hello World
B. Hello World Hello
C. Hello Hello World
D. All are wrong

HienLTH – KhietLTN Web Design 70


Question 16: said the results of the command
segment?
<?php
for ($i = 0; $i < 10; $i++) { for ($j = 0;
$j < 3; $j++) {
if (($j + $i) % 5 == 0) { break 2;
}
}
}
echo $j + $i;
?>
A. 0
B. 1
C. 2
D. All are wrong
HienLTH – KhietLTN Web Design 71
Question 17: Said the results of the
command segment?
<?php
$a = array (1 => 1, 2 => 2, 0 => 3);
echo $a[0];
?>
A. 1
B. 2
C. 3
D. All are wrong

HienLTH – KhietLTN Web Design 72


Question 18: Choose to declare array b so
that the output is bool (true)?
<?php
$a = array (1,2,3);
key
var_dump ($a == $b);
?>
A. $b = array (1 => 2, 2 => 3, 0 => 1);
B. $b = array (2 => 3, 1 =>2, 0 => 1);
C. $b = array ('0' => 1, '1' =>2, '2' => 3);
D. All right

HienLTH – KhietLTN Web Design 73


Question 19: Which function instead of the
following key causes the value a to update
to 3?
<?php
key
var_dump ($a == $b);
$a = 5; f($a);
echo $a;
?>
A. function f($a){global $a;$a = 3;return $a;}
B. function f(&$a){$a = 3;return $a;}
C. Both a and b are correct
D. A and B are wrong
HienLTH – KhietLTN Web Design 74
Question 20: Select the correct statement instead
of the key word so that the output is ‘def '?
<?php
$s = 'abcdef';
for ($i = 0; $i < key; $i++) { if ($s[$i] >
'c') {
echo $s[$i];
}
}
?>
A. strlen ($s)
B. count ($s)
C. $s.length
D. $s.count

HienLTH – KhietLTN Web Design 75


8. Control structure

• Điều kiện if
• Điều khiển switch
• Vòng lặp for Tương tự như C++
• Vòng lặp while
• Vòng lặp do.. While
• Vòng lặp foreach
• Từ khóa break, continue

HienLTH – KhietLTN Web Design 76


8.1 The if statement

if (conditional expression)
command block 1
else
command block 2

HienLTH – KhietLTN Web Design 77


8.1 The if statement

if ($a > $b) {


echo "a > b";
$a = $b;
} else {
echo "a <= b";
$b = $a;
}

HienLTH – KhietLTN Web Design 78


8.2 The switch statement

switch (expressions)
{
case expressions 1:
command block 1
case expressions 2:
command block 2
...
case expressions n:
command block n
default:
command block end
}
HienLTH – KhietLTN Web Design 79
8.2 The switch statement
switch ($a) {
case 0:
echo "a = 0";
break;
case 1:
echo "a = 1";
break;
}
HienLTH – KhietLTN Web Design 80
8.3 While / do ... while loop

while (conditional expression)


command block
Or:
do
command block
while (conditional expression);

HienLTH – KhietLTN Web Design 81


For example while loop

For example:

$i = 1; $j = 9;

while ($i <= 10) {

$temp = $i * $j;

print “$j * $i =
$temp<br>";

$i++;

HienLTH – KhietLTN Web Design 82


8.3 While / do ... while loop

while ($i++ < 5) {


switch ($i) {
case 2:
echo "At 2"; break;
case 5:
echo "At 5"; break 2;
default:
break;
}
}
HienLTH – KhietLTN Web Design 83
8.4 For loop

for (expression 1; expression 2; expression 3)


command block;

• Expression 1: executed once at the beginning of the


loop
• Expression 2: the iteration condition, considered before
each iteration
• Expression 3: executed after each iteration

HienLTH – KhietLTN Web Design 84


8.4 For loop

▪ For example:
print “<select>”;
for ($i = 1; $i <= 12; $i++)
{
print
“<option>$i</option>”;
}
print “</select>”;

HienLTH – KhietLTN Web Design 85


8.5 Repeat with for & foreach

for ($i=1, $j=0; $i<=10; $j+=$i, print $i,


$i++);

$arr = array(1, 2, 3, 4);


foreach ($arr as &$value) {
$value = $value * 2;
}

$arr = array("one", "two", "three");


foreach ($arr as $key => $value) {
echo "Key: $key; Value: $value";
}
HienLTH – KhietLTN Web Design 86
8.5 Repeat with for & foreach
foreach (array as variable)
{
statements
}

For example:

$meal = array('breakfast' => 'Walnut Bun',


'lunch' => 'Cashew Nuts and White Mushrooms',
'dinner' => 'Eggplant with Chili Sauce');

print "<table border=‘1’>\n";


foreach ($meal as $key => $value) {
print "<tr><td>$key</td><td>$value</td></tr>\n";
}
print '</table>';
HienLTH – KhietLTN Web Design 87
8.6 Loop stop commands

• break
Stop and exit the current loop
• continue
Stop performing the current iteration to go to
the next iteration

HienLTH – KhietLTN Web Design 88


8.7 For example
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>

<?php
$arr = array("one", "two", "three");
reset($arr);// reset pointer, start again on first element
while (list(, $value) = each($arr)) {
echo "Value: $value<br />\n";
}

foreach ($arr as $value) {


echo "Value: $value<br />\n";
}
?>
HienLTH – KhietLTN Web Design 89
8.7 For example
<?php
$arr = array("one", "two", "three");
reset($arr);
while (list($key, $value) = each($arr)) {
echo "Key: $key; Value: $value<br />\n";
}

foreach ($arr as $key => $value) {


echo "Key: $key; Value: $value<br />\n";
}
?>

Key: 0; Value: one


Key: 1; Value: two
Key: 2; Value: three
Key: 0; Value: one
Key: 1; Value: two
HienLTH – KhietLTN Key: 2; Value:
Webthree
Design 90
9. Function
<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}

$input = array(4,7);
takes_array($input);
?>

<?php
Note: dấu &
function add_some_extra(&$string)
{
$string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str;// outputs 'This is a string, and something extra.'
?>

HienLTH – KhietLTN Web Design 91


9. Function
function functionName ([parameter1]...[,parameterN])
{
statement[s] ;
}
function functionName ([parameter1]...[,parameterN])
{
statement[s] ;
return ….. ;
}
• Call the function
Enter the function name (not case sensitive)
and supply the necessary parameters in the ()
HienLTH – KhietLTN Web Design 92
9. Function
• Finish and return results
The return statement is used to terminate and return the
results as well as the right to render to where the function
was called. If no return statement, the default function
returns NULL value.
Want to return more than one value, you must use the array

• Parameter transmission
By default, parameters are passed inside the function by the
method of value. If you want to change directly on the
passed parameters, you use the reference method, add &
before the parameter name (when defining) as well as the
variable name passed as a parameter (when calling the
function).
HienLTH – KhietLTN Web Design 93
9. Function

• The parameter has a default value


Similar to declaring and assigning first value to a variable,
normally this paramater type should be last in the parameter list.
When calling a function if left blank in the parameter position with
a default value then default is used for that parameter.
• The function has an unknown number of parameters
Declare empty parameter list ()
Use the following functions to get the list of parameters:
func_num_args (): number of parameters when the function is
called
func_get_arg (i): value of the ith parameters passed (starting at 0)
func_get_args (): list of all parameters

HienLTH – KhietLTN Web Design 94


9. Function

• Static variable
Add static keyword when declaring variables
Initialized (and assigning values) a single first time during the
execution of the script
• Use global variables
Declare global variables with the keyword global (inside the
function) to be able to use this global variable inside the function.
Use the following functions to get the list of parameters:
func_num_args (): number of parameters when the function is
called
func_get_arg (i): value of the ith parameters passed (starting at 0)
func_get_args (): list of all parameters

HienLTH – KhietLTN Web Design 95


9. Function

• Scope
Valid for use throughout script, even before and
after definition

• Nested functions
Allows defining function nested, even nested
inside a control structure (if, switch, while / do,
while ...)
This type of function is scoped throughout the
script and cannot be redefined

HienLTH – KhietLTN Web Design 96


9. Function
<?php
function makecoffee($type = "cappuccino")
{
return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
?>
<?php
function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL)
{
$device = is_null($coffeeMaker) ? "hands" : $coffeeMaker;
return "Making a cup of ".join(", ", $types)." with $device.\n";
}
echo makecoffee();
echo makecoffee(array("cappuccino", "lavazza"), "teapot");
?>

HienLTH – KhietLTN Web Design 97


9. Function
<?php
function makeyogurt($type = "acidophilus", $flavour)
{
return "Making a bowl of $type $flavour.\n";
}

echo makeyogurt("raspberry");// won't work as expected


?>
<?php
function makeyogurt($flavour, $type = "acidophilus")
{
return "Making a bowl of $type $flavour.\n";
}

echo makeyogurt("raspberry"); // works as expected


?>
HienLTH – KhietLTN Web Design 98
9. Function
<?php <?php
function square ($num) function &returns_reference()
{ {
return $num * $num; return $someref;
} }
echo square (4);//outputs '16‘ $newref=&returns_reference();
?> ?>

<?php
function small_numbers()
{
return array (0, 1, 2);
}
list($zero,$one,$two)=small_numbers();
?>

HienLTH – KhietLTN Web Design 99


9. Function
<?php
function foo() {
echo "In foo()<br />\n";
}
function bar($arg = '')
{
echo "In bar(); argument was '$arg'.<br />\n";
}
// This is a wrapper function around echo
function echoit($string)
{
echo $string;
}
$func = 'foo';
$func(); // This calls foo()

$func = 'bar';
$func('test'); // This calls bar()

$func = 'echoit';
$func('test'); // This calls echoit()
?>

HienLTH – KhietLTN Web Design 100


9. Function
<?php
class Foo
{
function Variable()
{
$name = 'Bar';
$this->$name(); // This calls the Bar() method
}

function Bar()
{
echo "This is Bar";
}
}
$foo = new Foo();
$funcname = "Variable";
$foo->$funcname(); // This calls $foo->Variable()
?>

HienLTH – KhietLTN Web Design 101


10. Range of variables
<?php
$a = 1; $b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>
<?php
3
$a = 1;
$b = 2;
function Sum()
{
$GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"];
}
Sum();
echo $b;
?>
HienLTH – KhietLTN Web Design 102
10. Range of variables
<?php
$a = 1;
include "b.inc";
?>
Phạm vi của biến [a] có tác dụng trong cả b.inc
----------------------------------------------
<?php
$a = 1; // global scope
function Test()
{
echo $a;// reference to local scope variable
}
Test();
?>
Biến [a] ở ngoài và trong hàm Test khác nhau

HienLTH – KhietLTN Web Design 103


10. Range of variables

Variable name Description

$GLOBALS contains all the global variables that the local script can access

$_SERVER Contains information about the web server environment


$_GET contains information of GET requests
$_POST ccontains information of POST requests
$_COOKIE Contains information from HTTP cookies
$_FILES contains information from the file uploads POST
Contains information about the execution environment of the
$_ENV
script
$_REQUEST contain information entered by the user
$_SESSION
HienLTH – KhietLTNContains information ofWeb
registered
Design sessions 104
For example
<?php <?php
function Test() function Test()
{ {
$a = 0; static $a = 0;
echo $a; echo $a;
$a++; $a++;
} }
Test(); Test();
Test(); Test();
?> ?>

HienLTH – KhietLTN
? Web Design 105
Reference

• Website W3school
• Slide lập trình Web, ĐH KHTN, 2007

HienLTH – KhietLTN Web Design 106


Q&A

HienLTH – KhietLTN Web Design 107


THE END

HienLTH – KhietLTN Web Design 108


Discuss

▪ Họ tên:
▪ Mã SV:
▪ Lớp:
▪ Khoá:
▪ Email:

01 02 … 19 20

HienLTH – KhietLTN Web Design 109


Question 1: Which of the following PHP
lines of code is not valid?
A. $_10
B. ${“MyVar”}
C. &$something
D. $10_somethings

HienLTH – KhietLTN Web Design 110


Question 2: Said the results of the command segment?
<?php
define("myvalue","10");
$myarray[10]= "Dog";
$myarray[] ="Human";
$myarray['myvalue'] = "Cat";
$myarray["Dog"]= "Cat"; print
"The value is:";
print $myarray[myvalue]."\n";
?>
A. The value is: Dog
B. The value is: Cat
C. The value is: Human
D. $10_somethings
HienLTH – KhietLTN Web Design 111
Question 3: Said the results of the command
segment?
<?php
$a = 10; $b = 20; $c = 4;
$d = 8;
$f = $c + $d * 2;
$g = $f % 20;
$h = $b - $a + $c + 2; print $h;
?>
A. 42
B. 16
C. 18
D. All are wrong

HienLTH – KhietLTN Web Design 112


Question 4: Said value to be assigned to the variable $ a, $ b, $ c to
ex paragraph the words "Hello, World!"?
<?php
$string= "Hello, World!";
$a =???; $b =???; $c =???;
if($a) {
if($b &&!$c){ echo "Goodbye Cruel World!";
} else if(!$b &&!$c) { echo "Nothing here"; }
} else { if(!$b) {
if(!$a && (!$b && $c)) {echo"Hello, World!";
} else { echo"GoodbyeWorld!"; }
} else { echo "Not quite."; }
}
?>
A. false, true, false
B. true, true , false
C. false, true, true
D. false, false, true
HienLTH – KhietLTN Web Design 113
Question 5: Said the results of the command
segment?
<?php
$array = '0123456789ABCDEFG';
$s ='';
for ($i = 1; $i < 50; $i++) {
$s .=$array[rand(0,strlen ($array) - 1)];
}
echo $s;
?>
A. Export the chain has 49 random letters
B. Export 49-character string 'G'
C. Export the chain has 50 random letters
D. Error because $ array is not an array.

HienLTH – KhietLTN Web Design 114


Question 6: Said the results of the
command segment?
<?php
$array = array ('1', '2'); foreach
($array as $k => $v) {
echo ($k+$v)." ";
}
?>
A. 1 2
B. 0 1
C. 1 3
D. All are wrong

HienLTH – KhietLTN Web Design 115


Question 7: Which function to reverse
array content?
<?php
$array = array ('a', 'b','c', 'd');
?>
➔ output: 'd', 'c','b', 'a'
A. rsort()
B. array_reverse()
C. Both A and B are correct
D. All are wrong

HienLTH – KhietLTN Web Design 116


Question 8: Which function to reverse array
content?
<?php
$array = array (0.1=>'a', 0.2=>'b'); echo
count($array);
?>
A. 1
B. 2
C. 0
D. The statement has a wrong syntax

HienLTH – KhietLTN Web Design 117


Question 9: Said the results of the command
segment?
<?php
$array = array (1, 2, 3, 5, 8, 13, 21);
$sum= 0;
for ($i= 0;$i < 3;$i++) {
$sum+=$array[$array[$i]];
}
echo $sum;
?>
A. NULL
B. 10
C. 19
D. Error command

HienLTH – KhietLTN Web Design 118


Question 10: For commands instead of
key to output the string "php"?
<?php
$alpha = 'abcdefghijklmnopqrstuvwxyz';
$letters =array(15, 7, 15);
foreach($letters as $val) {
key
}
?>
A. echo chr($val);
B. echo substr($alpha, $val, 2);
C. echo $alpha{$val};
D. echo $alpha{$val+1};
HienLTH – KhietLTN Web Design 119
Question 11: Which statement is used to
concatenate 2 strings?
A. $s1 +$s2
B. "{$s1}{$s2}"
C. $s1.$s2
D. Both A and B are correct

HienLTH – KhietLTN Web Design 120


Question 12: For the string $ s =
"[email protected]", what command can you
use to extract the substring "gmail.com"?
A. substr($s,strpos($s, "@"));
B. strstr($s,"@");
C. substr($s,strpos($s, "@")+1);
D. strrpos($s, "@");

HienLTH – KhietLTN Web Design 121


Question 13: Said the results of the
following statements?
echo 'Testing ' . 1+ 2 . '45';
A. Testing 1245
B. Testing 345
C. Testing 1+245
D. 245

HienLTH – KhietLTN Web Design 122


Question 14 Which of the
following statements returns true?
A. 'top'==0
B. 123 =='123'
C. '1top' =='1'
D. Both A and B are correct

HienLTH – KhietLTN Web Design 123


Question 15: Said the results of the command
segment?
<?php
function hello($who = "World")
{
echo "Hello $who ";
}
hello(hello());
?>
A. Hello World
B. Hello World Hello
C. Hello Hello World
D. All are wrong
HienLTH – KhietLTN Web Design 124
Question 16: Said the results of the command
segment?
<?php
for ($i = 0; $i < 10; $i++) { for ($j = 0; $j <
3; $j++) {
if (($j + $i) % 5 == 0) { break 2;
}
}
}
echo $j + $i;
?>
A. 0
B. 1
C. 2
D. All are wrong
HienLTH – KhietLTN Web Design 125
Question 17: Said the results of the
command segment?
<?php
$a = array (1 => 1, 2 => 2, 0 => 3);
echo $a[0];
?>
A. 1
B. 2
C. 3
D. All are wrong

HienLTH – KhietLTN Web Design 126


Question 18: Choose to declare array b so
that the output is bool (true)?
<?php
$a = array (1,2,3);
key
var_dump ($a == $b);
?>
A. $b = array (1 => 2, 2 => 3, 0 => 1);
B. $b = array (2 => 3, 1 =>2, 0 => 1);
C. $b = array ('0' => 1, '1' =>2, '2' => 3);
D. All right

HienLTH – KhietLTN Web Design 127


Question 19: Which function instead of the
following key causes the value a to update to 3?
<?php
key
var_dump ($a == $b);
$a = 5; f($a);
echo $a;
?>
A. function f($a){global $a;$a = 3;return $a;}
B. function f(&$a){$a = 3;return $a;}
C. Both A and B are correct
D. Both A and B are wrong

HienLTH – KhietLTN Web Design 128


Question 20: Select the correct statement instead of
the key word so that the output is ‘def '?
<?php
$s = 'abcdef';
for ($i = 0; $i < key; $i++) { if
($s[$i] > 'c') {
echo $s[$i];
}
}
?>
A. strlen ($s)
B. count ($s)
C. $s.length
D. $s.count
HienLTH – KhietLTN Web Design 129
Thank you!!!

HienLTH – KhietLTN Web Design 130

You might also like