Professional Documents
Culture Documents
PHP ( TEST )
Mc Lc
Chapter 1 : Gii Thiu PHP
Chapter 2 : Bt u Vi PHP
Chapter 3 : Ci t PHP
Chapter 4 : C Php PHP
Chapter 5 : Bin PHP
Chapter 6 : Chui Bin PHP
Chapter 7 : Ton T PHP
Chapter 8 : Cu lnh if else trong PHP .
Chapter 9 : Cu lnh Switch trong PHP
Chapter 10 : Arrays ( Mng )
Chapter 11 : Looping While Loops
Chapter 12 : Looping For Loops
Chapter 13 : Functions ( Hm Chc Nng )
Chapter 14 : PHP Forms and User Input
Chapter 15 : PHP $_GET Variable
Chapter 16 : PHP $_POST Function
Chapter 17 : Date() Function
Chapter 18 : File Handing
Chapter 19 : File Upload
Chapter 20 : PHP Cookies
Chapter 21 : PHP Sessions
Chapter 22 : Sending Emails
Chapter 23 : Secure E-mails
Chapter 24 : Error Handing
Chapter 25 : Exception Handing
Chapter 26 : PHP Filter
Chapter 27 : PHP MySQL
Chapter 28 : PHP XML Expat Parser
Chapter 29 : Gii thiu AJAX
Chapter Ngoi : Bi Tp
-Bi 11: Vit ng dng ng nhp bng PHP v MYSQL
-Bi 12: Vit ng dng thm thnh vin bng PHP v MYSQL
-Bi 13: Vit ng dng qun l thnh vin bng PHP v MYSQL
-Bi 14: vit ng dng sa xa thnh vin bng PHP v MYSQL
-Bi 15: Vit ng dng to m xc nhn bng PHP
-Bi 16: Vit ng dng m s ngi online bng php
Page 1 of 413
Page 2 of 413
Page 3 of 413
<!DOCTYPE html>
<html>
<body>
<?php
echo "My first PHP script!";
?>
</body>
</html>
Chapter 2 : Bt u vi PHP
Nhng g bn nn bit !!!
Trc khi tip tc, bn cn phi c mt s hiu bit c bn sau y:
-HTML
-Javascript
Nu bn mun nghin cu cc i tng ny ln u tin, tm thy cc hng dn trn
trang ny .
http://w3schools.com/
PHP l g?
-PHP l vit tt ca PHP: Hypertext Preprocessor
-PHP l mt ngn ng s dng rng ri , l mt m ngun m
-PHP c thc hin trn my ch ( vd : Linux )
-PHP hon ton min ph download v s dng
PHP l ngn ng n gin nht cho ngi mi bt u hc lp trnh
PHP cng cung cp nhiu tnh nng tin tin cho cc lp trnh vin chuyn nghip.
File PHP l g?
-PHP tp tin c th cha vn bn, HTML, JavaScript m, v m PHP
-M PHP c thc hin trn my ch, v kt qu c tr v cho trnh duyt nh
Page 4 of 413
HTML
-PHP tp tin c phn m rng tp tin mc nh ca ". Php"
PHP c th lm g?
-PHP c th to ra ni dung trang nng ng
-PHP c th to ra, m, c, vit, v cc tp tin trn my ch gn
-PHP c th thu thp d liu mu
-PHP c th gi v nhn cookie
-PHP c th thm, xa, sa i d liu trong c s d liu ca bn
-PHP c th hn ch ngi dng truy cp mt s trang trn trang web ca bn
-PHP c th m ha d liu
Vi PHP, bn khng gii hn u ra HTML. Bn c th xut hnh nh, tp tin PDF, v
thm ch c phim Flash. Bn cng c th sn xut bt k vn bn, chng hn nh
XHTML v XML.
Ti sao PHP?
- PHP chy trn cc nn tng khc nhau (Windows, Linux, Unix, Mac OS X, vv)
- PHP l tng thch vi hu nh tt c cc my ch c s dng hin nay (Apache,
IIS, vv)
- PHP h tr cho mt lot cc c s d liu
- PHP l min ph. Ti v n t ngun PHP chnh thc: www.php.net
- PHP l d dng tm hiu v chy hiu qu pha my ch
Chapter 3 : Ci t PHP
Nhng g bn cn c !
+ Tm 1 Hosting ( chy php , ci ny p dng cho ai mun thu host b tin mnh
khuyn nn chy localhost )
+ Bn c th dng cc chng trnh h tr chy localhost trn google , c rt nhiu v
bn c th ty chn nu thch
i vi vic Chn Hosting
- Bn nn chn hosting no h tr tt v t vn khch hng ( v l yu t cn
thit )
- Bn nn chn hosting no c tc load nhanh , h tr ng truyn tt v khng
b cm cc hm ( Function ) to iu kin tt nht cho vic hc PHP
Page 5 of 413
V D
<?php
M lnh php s y
?>
Phn m rng tp tin mc nh cho cc tp tin PHP l ".php"
Mt file PHP thng thng c cha cc th HTML, v mt s m kch bn PHP.
Di y, chng ti c mt v d ca mt kch bn PHP n gin m s gi vn bn
"Hello World!" cho trnh duyt:
<?php
echo Hello World!;
?>
V d :
<!DOCTYPE html>
<html>
<body>
<?php
//y l ch thch 1 dng
/*
y l ch thch
Nhiu
Dng
*/
?>
Bin PHP
Vi i s, cc bin PHP c s dng gi cc gi tr hoc biu thc.
Mt bin c th c mt tn ngn, nh x, hoc mt ci tn di hn, nh h v
tn chng ta vy.
Quy tc cho tn bin PHP :
-Cc bin trong PHP bt u vi mt k hiu $, tip theo l tn ca bin
-Tn bin phi bt u vi mt k t hoc k t gch di
-Mt tn bin ch c th cha cc k t ch-s v gch di (A-z, 0-9, v _)
-Mt tn bin khng nn cha khng gian ( gi l khong cch vd : $a b
bin ny l sai , $ba th ny mi ng )
-Tn bin l trng hp nhy cm v quan trng nn n phn bit c hoa v
thng (y v Y l hai bin khc nhau)
Page 7 of 413
Phm Vi PHP
Phm vi ca mt bin l mt phn ca kch bn, trong bin c th c
tham chiu.
Page 8 of 413
Phm Vi Local
Mt bin khai bo trong mt hm PHP l a phng v ch c th
c truy cp trong phm vi chc nng . (Bin c phm vi local): V
d .
<?php
$a = 5; // phm vi local
function myTest()
{
echo $a; // phm vi local
}
myTest();
?>
Phm Vi Global
Phm vi ton cu cp n bt k bin c nh ngha bn ngoi
ca bt k chc nng.
Bin ton cu c th c truy cp t bt k mt phn ca kch bn
khng phi l bn trong mt hm.
truy cp vo mt bin ton cu t bn trong mt chc nng, s
dng global t kha:
Page 9 of 413
V d :
<?php
$a = 5;
$b = 10;
function myTest()
{
global $a, $b;
$b = $a + $b;
}
myTest();
echo $b;
?>
Page 10 of 413
Phm Vi Static
Khi mt hm c hon thnh, tt c cc bin ca n thng b xa. Tuy nhin, i khi bn
mun bin a phng khng b xa.
lm iu ny, s dng cc t kha tnh khi ln u tin bn khai bo cc bin:
static $rememberMe;
Sau , mi khi hm c gi, bin vn s c nhng thng tin n c t thi gian qua cc
chc nng c gi.
Parameters
Mt tham s l mt bin a phng c gi tr c truyn cho hm m gi.
Cc thng s c khai bo trong danh sch tham s nh l mt phn ca vic k khai hm
functions:
Function myTest($para1,$para2,...)
{
// function code
}
Cc thng s cn c gi l i s. Chng ti s tho lun chi tit hn khi chng ta ni v cc
chc nng.
Page 11 of 413
<?php
$txt="Hello World";
echo $txt;
?>
Hm strlen()
Hm strlen () c s dng tr li chiu di ca mt chui.
Hy tm chiu di ca mt chui:
<?php
echo strlen("Hello world!");
?>
Kt qu tr v l
12
Chiu di ca mt chui thng c s dng trong vng lp hoc cc chc nng khc,
iu quan trng l bit khi no kt thc chui. (tc l trong mt vng lp, chng ti
mun ngng vng lp sau khi k t cui cng trong chui).
Hm strpos()
Hm strpos () c s dng tm kim mt nhn vt / vn bn trong mt chui.
Nu kt hp c tm thy, chc nng ny s tr li vi v tr nhn vt ca trn u u
Page 12 of 413
<?php
echo strpos("Hello world!","world");
?>
Kt qu tr v l
6
V tr t "world" trong v d trn l 6. L do m n l 6 (v khng phi 7), l v tr ca k
t u tin trong chui l 0, v khng phi 1.
Thng tin v 1 s chc nng ca cc hm khc ( c th l khng y nhng cng nn
c qua cho bit )
http://w3schools.com/php/php_ref_string.asp
Modulus . Chia
ly s d
Description
Sum of x and y
Difference of x and y
Example
2+2
5-2
Result
4
3
Product of x and y
5*2
10
Quotient of x and y
15 / 5
5%2
10 % 8
10 % 2
-2
3
1
2
0
"Hi" . "Ha"
HiHa
Remainder of x divided
by y
Negation . s m Opposite of x
Concatenation .
Concatenate two strings
Ghp k t
Page 13 of 413
x=y
x += y
x -= y
x *= y
x /= y
x %= y
a .= b
x=x+y
x=x-y
x=x*y
x=x/y
x=x%y
a=a.b
Description
The left operand gets set to the value of the expression on
the right
Addition
Subtraction
Multiplication
Division
Modulus
Concatenate two strings
Ton T So Snh
Comparison operators allows you to compare two values:
Operator Name
x == y
Equal
x === y
Identical
x != y
x <> y
Not equal
Not equal
x !== y
Not identical
x>y
x<y
Greater than
Less than
Greater than or
equal to
Less than or
x >= y
x <= y
Page 14 of 413
Description
True if x is equal to y
True if x is equal to y, and they
are of same type
True if x is not equal to y
True if x is not equal to y
True if x is not equal to y, or
they are not of same type
True if x is greater than y
True if x is less than y
True if x is greater than or equal
to y
True if x is less than or equal to
Example
5==8 returns false
5==="5" returns false
5!=8 returns true
5<>8 returns true
5!=="5" returns true
5>8 returns false
5<8 returns true
5>=8 returns false
5<=8 returns true
equal to
Logical Operators
Operator Name
x and y
And
x or y
Or
x xor y
Xor
x && y
And
x || y
Or
!x
Not
Description
Example
x=6
y=3
True if both x and y are true
(x < 10 and y > 1) returns
true
x=6
True if either or both x and y are y=3
true
(x==6 or y==5) returns
true
x=6
True if either x or y is true, but y=3
not both
(x==6 xor y==3) returns
false
x=6
y=3
True if both x and y are true
(x < 10 && y > 1) returns
true
x=6
True if either or both x and y are y=3
true
(x==5 || y==5) returns
false
x=6
True if x is not true
y=3
!(x==y) returns true
Array Operators
Operator Name
x+y
Union
x == y
Equality
x === y
Identity
x != y
x <> y
x !== y
Inequality
Inequality
Non-identity
Page 15 of 413
Description
Union of x and y
True if x and y have the same key/value pairs
True if x and y have the same key/value pairs in the same
order and of the same types
True if x is not equal to y
True if x is not equal to y
True if x is not identical to y
Cu lnh IF
- S dng cu lnh if khi thc hin mt s m khi v ch khi iu kin
qui nh ca n ng vi m c qui nh
C php cu if :
If ( iu kin ) s c thc hin nu iu kin ng .
V d sau y s a ra "Have a nice weekend!" nu ngy hin nay l th Su:
Page 16 of 413
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri") echo "Have a nice weekend!";
?>
</body>
</html>
Cu lnh IF ELSE
S dng cu lnh if else thc hin on m nu iu kin n l ng
hoc sai .
C php :
if (iu kin)
{
M lnh s c thc hin nu iu kin ng;
}
else
{
M lnh s c thc hin nu iu kin sai;
}
V d
V d sau y s a ra "Have a nice weekend!" nu ngy hin nay l th Su, nu khng
phi n s tr kt qu khc l "Have a nice day!"
Page 17 of 413
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
{
echo "Have a nice weekend!";
}
else
{
echo "Have a nice day!";
}
?>
</body>
</html>
C php
if (iu kin 1)
{
code s c thc hin nu iu kin 1 ng;
}
elseif (iu kin 2)
{
code s c thc hin nu iu kin 2 ng;
}
else
{
code s c thc hin nu my ci iu kin trn sai;
}
V d
Page 18 of 413
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
{
echo "Have a nice weekend!";
}
elseif ($d=="Sun")
{
echo "Have a nice Sunday!";
}
else
{
echo "Have a nice day!";
}
?>
</body>
</html>
C php
Page 19 of 413
switch (n)
{
case label1:
code s thc hin nu n=label1;
break;
case label2:
code s thc hin nu if n=label2;
break;
default:
code s thc hin nu n khc c 2 ci label1 v label2;
}
y l cch n hot ng: u tin chng ta c mt biu thc duy nht n (thng xuyn
nht mt bin), c nh gi mt ln. Gi tr ca biu thc sau c so snh vi cc
gi tr cho tng trng hp trong cu trc. Nu c mt trn u, cc khi m lin kt vi
trng hp c thc hin. S dng break ngn chn cc m t chy vo trng
hp tip theo t ng. Nhng tuyn b mc nh c s dng nu khng tm thy.
V d
Page 20 of 413
<html>
<body>
<?php
$x=1;
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
}
?>
</body>
</html>
Page 21 of 413
Tuy nhin , nu khng phi 3 ci tn m l hng ngn ci tn th sao ? Gii php tt nht
l dng mng
Mt mng c th gi tt c cc gi tr bin ca bn di mt ci tn. V bn c th truy
cp vo cc gi tr bng cch cp n tn mng.
Mi phn t trong mng c ch s ring ca mnh n c th d dng truy cp.
Trong PHP, c ba loi ca cc mng:
Numeric array - Mt mng vi mt s ch s
Associative array - Mt mng m mi phm ID c kt hp vi mt gi tr
Multidimensional array- Mt mng c cha mt hoc nhiu mng
Numeric Arrays
Mt mng s cc ca hng mi phn t mng vi mt s ch s.
C hai phng php to ra mt mng s.
1. Trong v d sau ch s c gn t ng (ch s bt u t 0):
$cars=array("Saab","Volvo","BMW","Toyota");
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
Page 22 of 413
V d
Trong v d sau bn truy cp cc gi tr bin bng cch cp n tn mng v ch s:
<?php
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
echo $cars[0] . " and " . $cars[1] . " are Swedish cars.";
?>
Code s tr v l
Saab and Volvo are Swedish cars.
Associative Arrays
Mt mng kt hp, mi phm ID c kt hp vi mt gi tr.
Khi lu tr d liu v cc gi tr c th c t tn, mt mng s khng phi l lun
lun l cch tt nht lm iu .
Vi mng kt hp, chng ti c th s dng cc gi tr nh l cha kha v gn gi tr cho
h.
V d 1
Trong v d ny, chng ti s dng mt mng gn la tui ngi khc nhau:
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
V d 2
V d ny l tng t nh v d 1, nhng cho thy mt cch khc nhau ca vic to ra cc
mng:
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
Page 23 of 413
Multidimensional Arrays
Trong mt mng a chiu, mi phn t trong mng chnh cng c th l mt mng. V
mi phn t trong mng ph c th l mt mng, v nh vy.
V d
Trong v d ny, chng ta to mt mng a chiu, vi cc phm ID t ng gn:
Page 24 of 413
$families = array
(
"Griffin"=>array
(
"Peter",
"Lois",
"Megan"
),
"Quagmire"=>array
(
"Glenn"
),
"Brown"=>array
(
"Cleveland",
"Loretta",
"Junior"
)
);
Page 25 of 413
Array
(
[Griffin] => Array
(
[0] => Peter
[1] => Lois
[2] => Megan
)
[Quagmire] => Array
(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
)
V d 2
Cho php th hin th mt gi tr t mng trn:
echo "Is " . $families['Griffin'][2] .
" a part of the Griffin family?";
Kt qu tr v s l
Is Megan a part of the Griffin family?
Page 26 of 413
Page 27 of 413
Kt qu l
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
do
{
code s c thc hin;
}
while (iu kin);
V d
V d di y u tin thit lp mt bin 1 ($i=1;).
Sau , n bt u do ... trong khi vng lp. Cc vng lp s tng bin i vi 1, v sau
vit mt s u ra. Sau , iu kin c kim tra (l ti t hn, hoc bng 5), v vng
lp s tip tc chy khi i nh hn hoc bng 5
Page 28 of 413
<html>
<body>
<?php
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br>";
}
while ($i<=5);
?>
</body>
</html>
Kt qu cho ra l
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
Page 29 of 413
Ch thch:
init: Hu h s dng s m (nhng c th c bt k
m c thc hin mt ln vo u ca vng lp)
condition: iu kin cho mi ln lp. Nu iu kin
ny ng, vng lp tip tc. Nu n iu kin sai th
vng lp kt thc.
increment: Hu ht tng s m (nhng c th c
bt k m s c thc hin vo cui ca s lp li)
Lu : Cc thng s init v increment c th c sn
phm no hoc c nhiu biu ng (cch nhau bng du
phy).
V d
V d di y nh ngha mt vng lp bt u vi i = 1. Cc vng lp s tip tc chy
min l bin i nh hn hoc bng 5. Bin i s tng thm 1 mi ln vng lp chy:
Page 30 of 413
<html>
<body>
<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . "<br>";
}
?>
</body>
</html>
Kt qu tr v l
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
Page 31 of 413
<html>
<body>
<?php
$x=array("one","two","three");
foreach ($x as $value)
{
echo $value . "<br>";
}
?>
</body>
</html>
Kt qu tr v s l
one
two
three
Chapter 13 : Functions ( Hm
Chc Nng )
Sc mnh thc s ca PHP xut pht t chc nng ca mnh.
Trong PHP, c hn 700 tch hp chc nng.
Bn c th tham kho cc chc nng nhiu hn y
http://w3schools.com/php/default.asp
PHP Functions
Trong chng ny, chng ti s cho bn thy lm th no to ra cc chc nng ca
ring bn. gi cho kch bn ang c thc thi khi ti trang, bn c th t n vo mt
hm.Chc nng s c thc hin bi mt cuc gi n chc nng.
Bn c th gi mt chc nng t bt c ni no trong mt trang .
Page 32 of 413
thm nhiu chc nng cho mt hm, chng ta c th thm cc thng s. Mt tham s
l ging nh mt bin.
Tham s c quy nh c th sau tn hm, bn trong du ngoc n.
V d 1
V d sau y s vit tn khc nhau u tin, nhng tn cui cng nh nhau:
<html>
<body>
<?php
function writeName($fname)
{
echo $fname . "
Refsnes.<br>";
}
echo "My name is ";
writeName("Kai Jim");
echo "My sister's name is ";
writeName("Hege");
echo "My brother's name is ";
writeName("Stale");
?>
</body>
</html>
Kt qu s l
Page 34 of 413
<html>
<body>
<?php
function writeName($fname,$punctuation)
{
echo $fname . " Refsnes" . $punctuation . "<br>";
}
echo "My name is ";
writeName("Kai Jim",".");
echo "My sister's name is ";
writeName("Hege","!");
echo "My brother's name is ";
writeName("Stle","?");
?>
</body>
</html>
Kt qu s l
My name is Kai Jim Refsnes.
My sister's name is Hege Refsnes!
My brother's name is Stle Refsnes?
Page 35 of 413
<html>
<body>
<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
</body>
</html>
Kt qu s l
1 + 16 = 17
Page 36 of 413
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="fname">
Age: <input type="text" name="age">
<input type="submit">
</form>
</body>
</html>
Khi mt ngi dng in vo cc hnh thc trn v nhp chut vo nt submit, cc d
liu mu c gi vo mt tp tin PHP, gi l "welcome.php":
"welcome.php" trng nh th ny:
<html>
<body>
Welcome <?php echo $_POST["fname"]; ?>!<br>
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>
Kt qu tr v s i loi nh th ny
Welcome John!
You are 28 years old.
Cc bin PHP $_POST v $_GET s c gii thch trong cc chng tip theo.
Form Validation
u vo s dng nn c xc nhn trn cc trnh duyt bt c khi no c th (theo lnh
ca khch hng). Trnh duyt xc nhn l nhanh hn v gim ti my ch.
Bn nn xem xt my ch xc nhn nu ngi dng nhp vo s c chn vo c s d
liu. Mt cch tt xc nhn mt hnh thc trn my ch l vit cc hnh thc cho
chnh n, thay v nhy n mt trang khc. Sau ngi dng s nhn c cc thng
Page 37 of 413
Page 39 of 413
Page 40 of 413
Parameter
format
timestamp
Description
Required. Specifies the format of the timestamp
Optional. Specifies a timestamp. Default is the current date and time
Page 41 of 413
Code s ra l
Tomorrow is 2009/05/12
Syntax ( C php )
include 'filename';
or
require 'filename';
<html>
<body>
<?php include 'header.php'; ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>
Page 43 of 413
V d 2
Gi s chng ta c mt tp tin trnh n tiu chun nn c s dng trn tt c cc
trang.
"menu.php":
<html>
<body>
<div class="leftmenu">
<?php include 'menu.php'; ?>
</div>
<h1>Welcome to my home page.</h1>
<p>Some text.</p>
</body>
</html>
V d 3
Gi s chng ta c mt tp tin vi mt s bin c nh ngha ("vars.php") bao gm:
Page 44 of 413
<?php
$color='red';
$car='BMW';
?>
<html>
<body>
<h1>Welcome to my home page.</h1>
<?php include 'vars.php';
echo "I have a $color $car"; // I have a red BMW
?>
</body>
</html>
Opening a File
Tham s u tin ca chc nng ny cha tn ca tp tin c m v tham s th hai quy
nh c th trong ch tp tin phi c m ra:
<html>
<body>
<?php
$file=fopen("welcome.txt","r");
?>
</body>
</html>
Page 45 of 413
Modes
r
r+
w
w+
a
a+
x
x+
Description
Read only. Starts at the beginning of the file
Read/Write. Starts at the beginning of the file
Write only. Opens and clears the contents of file; or creates a new file
if it doesn't exist
Read/Write. Opens and clears the contents of file; or creates a new file
if it doesn't exist
Append. Opens and writes to the end of the file or creates a new file if
it doesn't exist
Read/Append. Preserves file content by writing to the end of the file
Write only. Creates a new file. Returns FALSE and an error if file
already exists
Read/Write. Creates a new file. Returns FALSE and an error if file
already exists
<html>
<body>
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>
</body>
</html>
Closing a File
Chc nng fclose() dng ng file ang m:
Page 46 of 413
<?php
$file = fopen("test.txt","r");
//some code to be executed
fclose($file);
?>
Check End-of-file
Feof () chc nng kim tra nu "end-of-file (EOF) t c.
Feof () chc nng hu ch cho Looping thng qua cc d liu khng r chiu di.
Lu : Bn khng th c t tp tin m trong w, a, v ch x!
Page 47 of 413
<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). "<br>";
}
fclose($file);
?>
Page 48 of 413
Page 49 of 413
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
?>
Restrictions on Upload
Trong kch bn ny, chng ta thm mt s hn ch cc tp tin ti ln. Ngi s dng
c th ti ln gif, jpeg, v png tp tin v kch thc tp tin phi di 20 kB.:
Page 50 of 413
<?php
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
}
else
{
echo "Invalid file";
}
?>
Lu : i vi IE nhn ra loi tp tin jpg phi l pjpeg, cho FireFox n phi l
jpeg.
Page 51 of 413
<?php
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
Page 52 of 413
What is a Cookie?
Mt cookie thng c s dng xc nh mt ngi s dng. Mt cookie l mt file
nh m server nhng vo trn my tnh ca ngi dng. Mi ln cng mt my tnh yu
cu mt trang vi mt trnh duyt, n s gi cookie. Vi PHP, bn c th to ra v ly gi
tr cookie.
Page 53 of 413
<?php
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?>
<html>
.....
Page 54 of 413
<html>
<body>
<?php
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br>";
else
echo "Welcome guest!<br>";
?>
</body>
</html>
Page 55 of 413
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name">
Age: <input type="text" name="age">
<input type="submit">
</form>
</body>
</html>
<html>
<body>
Welcome <?php echo $_POST["name"]; ?>.<br>
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>
Page 56 of 413
Page 57 of 413
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>
<html>
<body>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>
Kt qu cho ra l
Pageviews=1
Trong v d di y, chng ti to ra mt truy cp trang page-views n gin. Cc
isset() chc nng kim tra nu bin "views" c thit lp. Nu "views" c thit
lp, chng ta c th tng truy cp ca chng ti. Nu "views" khng tn ti, chng ti to
ra mt bin "views", v t n vo 1:
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>
Destroying a Session
Nu bn mun xa mt s d liu phin ( sessions ), bn c th s dng unset() hoc
session_destroy() .
Page 58 of 413
Unset() chc nng c s dng gii phng bin phin giao dch quy nh:
<?php
session_start();
if(isset($_SESSION['views']))
unset($_SESSION['views']);
?>
Bn cng c th ph hy hon ton cc session bng cch gi session_destroy() chc
nng:
<?php
session_destroy();
?>
Lu : session_destroy () s thit lp li phin lm vic ca bn v bn s mt tt c cc
d liu sessions ca bn c lu tr.
Description
Required. Specifies the receiver / receivers of the email
Required. Specifies the subject of the email. Note: This parameter
cannot contain any newline characters
Required. Defines the message to be sent. Each line should be
separated with a LF (\n). Lines should not exceed 70 characters
Optional. Specifies additional headers, like From, Cc, and Bcc. The
additional headers should be separated with a CRLF (\r\n)
Optional. Specifies an additional parameter to the sendmail program
Page 60 of 413
<html>
<body>
<?php
if (isset($_REQUEST['email']))
//if "email" is filled out, send email
{
//send email
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
mail("someone@example.com", $subject,
$message, "From:" . $email);
echo "Thank you for using our mail form";
}
else
//if "email" is not filled out, display the form
{
echo "<form method='post' action='mailform.php'>
Email: <input name='email' type='text'><br>
Subject: <input name='subject' type='text'><br>
Message:<br>
<textarea name='message' rows='15' cols='40'>
</textarea><br>
<input type='submit'>
</form>";
}
?>
</body>
</html>
Page 61 of 413
chng k tip ca hng dn ny, bn c th c thm chi tit v l hng trong kch bn
e-mail, v lm th no xc nhn u vo ngi s dng lm cho n an ton hn.
Page 62 of 413
Page 63 of 413
<html>
<body>
<?php
function spamcheck($field)
{
//filter_var() sanitizes the e-mail
//address using FILTER_SANITIZE_EMAIL
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
//filter_var() validates the e-mail
//address using FILTER_VALIDATE_EMAIL
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
if (isset($_REQUEST['email']))
{//if "email" is filled out, proceed
//check if the email address is invalid
$mailcheck = spamcheck($_REQUEST['email']);
if ($mailcheck==FALSE)
{
echo "Invalid input";
}
else
{//send email
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
mail("someone@example.com", "Subject: $subject",
$message, "From: $email" );
echo "Thank you for using our mail form";
}
}
else
{//if "email" is not filled out, display the form
echo "<form method='post' action='mailform.php'>
Email: <input name='email' type='text'><br>
Subject: <input name='subject' type='text'><br>
Message:<br>
<textarea name='message' rows='15' cols='40'>
Page 64 of 413
</textarea><br>
<input type='submit'>
</form>";
}
?>
</body>
</html>
<?php
$file=fopen("welcome.txt","r");
?>
Nu tp tin khng tn ti, bn c th nhn c mt li nh th ny:
Warning: fopen(welcome.txt) [function.fopen]: failed to open stream:
No such file or directory in C:\www\test.php on line 2
trnh m ngi dng nhn c mt thng bo li nh trn, chng ti kim tra nu
tp tin tn ti trc khi chng ti c gng truy cp vo n:
<?php
if(!file_exists("welcome.txt"))
{
die("File not found");
}
else
{
$file=fopen("welcome.txt","r");
}
?>
By gi nu cc tp tin khng tn ti, bn nhn c mt li nh th ny:
File not found
on m trn l hiu qu hn hn so vi m trc , bi v n s dng mt c ch x l
li n gin ngn chn kch bn sau khi li.
Tuy nhin, ch cn dng li kch bn khng phi l lun lun ng cch i. Chng ta
hy xem xt thay th PHP chc nng cho cc li x l.
Page 66 of 413
Parameter
error_level
error_message
error_file
error_line
error_context
Description
Required. Specifies the error report level for the user-defined error.
Must be a value number. See table below for possible error report
levels
Required. Specifies the error message for the user-defined error
Optional. Specifies the filename in which the error occurred
Optional. Specifies the line number in which the error occurred
Optional. Specifies an array containing every variable, and their values,
in use when the error occurred
E_NOTICE
Page 67 of 413
Description
Non-fatal run-time errors. Execution of the script is
not halted
Run-time notices. The script found something that
might be an error, but could also happen when
running a script normally
256
E_USER_ERROR
Page 68 of 413
set_error_handler("customError");
T khi chng ti mun c chc nng ty chnh ca chng ti x l tt c cc li,
set_error_handler() ch cn mt tham s, mt tham s th hai c th c thm vo
xc nh mt mc li.
V d
Kim tra x l li bng cch c gng bin u ra khng tn ti:
<?php
//error handler function
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr";
}
//set error handler
set_error_handler("customError");
//trigger error
echo($test);
?>
u ra ca cc m trn nn c mt ci g nh th ny:
Error: [8] Undefined variable: test
Trigger an Error
Trong mt kch bn m ngi s dng c th nhp d liu n rt hu ch kch hot cc
li khi mt u vo bt hp php xy ra. Trong PHP, iu ny c thc hin bi cc
chc nng trigger_error().
V d
Trong v d ny, mt li xy ra nu bin "test" ln hn "1":
Page 69 of 413
<?php
$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below");
}
?>
u ra ca cc m trn nn c mt ci g nh th ny:
Notice: Value must be 1 or below
in C:\webfolder\test.php on line 6
Page 70 of 413
<?php
//error handler function
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Ending Script";
die();
}
//set error handler
set_error_handler("customError",E_USER_WARNING);
//trigger error
$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
u ra ca cc m trn nn c mt ci g nh th ny:
Error: [512] Value must be 1 or below
Ending Script
By gi chng ta hc c cch to ra cc li ca chng ta v lm th no kch
hot chng, cho php c mt ci nhn li ng nhp.
Error Logging
Theo mc nh, PHP s gi mt bn ghi li h thng ng nhp ca my ch hoc mt
tp tin, ty thuc vo cch cu hnh error_log c thit lp trong file php.ini. Bng cch
s dng cc error_log() chc nng bn c th gi cc bn ghi li vo mt tp tin c ch
nh hoc mt im n t xa.
Gi thng bo li cho chnh mnh bng e-mail c th l mt cch tt nhn c thng
bo li c th.
Page 71 of 413
<?php
//error handler function
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Webmaster has been notified";
error_log("Error: [$errno] $errstr",1,
"someone@example.com","From: webmaster@example.com");
}
//set error handler
set_error_handler("customError",E_USER_WARNING);
//trigger error
$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
u ra ca cc m trn nn c mt ci g nh th ny:
Error: [512] Value must be 1 or below
Webmaster has been notified
What is an Exception
Page 72 of 413
Page 73 of 413
<?php
//create function with an exception
function checkNum($number)
{
if($number>1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}
//trigger exception
checkNum(2);
?>
Page 74 of 413
tin ngoi l
<?php
//create function with an exception
function checkNum($number)
{
if($number>1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}
//trigger exception in a "try" block
try
{
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}
//catch exception
catch(Exception $e)
{
echo 'Message: ' .$e->getMessage();
}
?>
on m trn s nhn c mt li nh th ny:
Message: Value must be 1 or below
Example explained:
on m trn nm mt ngoi l v bt n:
1.Cc checkNum() chc nng c to ra. N kim tra nu mt s l s ln hn 1. Nu
Page 75 of 413
c, mt ngoi l c nm
2.Cc checkNum() chc nng c gi trong mt khi "th"
3.Ngoi tr trong phm vi chc nng checkNum () c nm
4.Block "bt" retrives cc trng hp ngoi l v to ra mt i tng ($e) c cha cc
thng tin ngoi l
5.Cc thng bo li t trng hp ngoi l c lp li bng cch gi $e->
getMessage() t i tng ngoi l
Tuy nhin, mt trong nhng cch c c xung quanh "nm mi phi c mt nm bt"
nguyn tc l thit lp mt mc ngoi l x l hng u x l cc li phiu
thng qua.
{
//throw exception if email is not
valid
throw new
customException($email);
}
}
catch (customException $e)
{
//display custom message
echo $e->errorMessage();
}
?>
Cc lp hc mi l mt bn sao ca lp ngoi l c vi mt s b sung chc nng
ErrorMessage(). V n l mt bn sao ca lp c, v n c tha hng cc thuc tnh
v phng php t lp c, chng ta c th s dng cc phng thc lp ngoi l nh
getline() v getFile() v getMessage().
Example explained:
on m trn nm mt ngoi l v bt n vi mt lp ngoi l ty chnh:
1.Lp customException() c to ra nh l mt phn m rng ca lp ngoi l c.
Bng cch ny, n c tha hng tt c cc phng php v cc thuc tnh t lp
ngoi l c
2.Chc nng ErrorMessage() c to ra. Hm ny tr v mt thng bo li nu mt
a ch e-mail khng hp l
3.Bin $email c thit lp mt chui khng phi l mt a ch e-mail hp l
4."Th" khi c thc hin v ngoi l c nm t a ch e-mail khng hp l
5.Khi "catch" bt nhng trng hp ngoi l v hin th cc thng bo li
Multiple Exceptions
N c th cho mt kch bn s dng nhiu trng hp ngoi l kim tra nhiu iu
kin.
C th s dng mt s nu .. khc khi, mt chuyn i, hoc nhiu trng hp ngoi l
lm t. Nhng trng hp ngoi l ny c th s dng cc lp hc ngoi l khc nhau v
tr li thng bo li khc nhau:
Page 77 of 413
<?php
class customException extends Exception
{
public function errorMessage()
{
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}
$email = "someone@example.com";
try
{
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{
//throw exception if email is not valid
throw new customException($email);
}
//check for "example" in mail address
if(strpos($email, "example") !== FALSE)
{
throw new Exception("$email is an example e-mail");
}
}
catch (customException $e)
{
echo $e->errorMessage();
}
catch(Exception $e)
{
echo $e->getMessage();
}
?>
Example explained:
Page 78 of 413
Re-throwing Exceptions
i khi, khi mt ngoi l c nm ra, bn c th mun x l n khc vi cch tiu
chun. N c th nm mt ngoi l ln th hai trong vng mt khi "catch".
Mt kch bn nn che giu li h thng t ngi dng. Li h thng c th quan trng i
vi cc coder, nhng khng c ngi dng quan tm. lm cho mi vic d dng hn
cho ngi s dng, bn c th nm li ngoi l vi mt thng ip thn thin vi ngi
s dng:
Page 79 of 413
<?php
class customException extends Exception
{
public function errorMessage()
{
//error message
$errorMsg = $this->getMessage().' is not a valid E-Mail address.';
return $errorMsg;
}
}
$email = "someone@example.com";
try
{
try
{
//check for "example" in mail address
if(strpos($email, "example") !== FALSE)
{
//throw exception if email is not valid
throw new Exception($email);
}
}
catch(Exception $e)
{
//re-throw exception
throw new customException($email);
}
}
catch (customException $e)
{
//display custom message
echo $e->errorMessage();
}
?>
Example explained:
on m trn bi kim tra nu a ch email c cha chui "v d" trong , nu c, cc
trng hp ngoi l c li nm:
Page 80 of 413
Page 81 of 413
ngoi l
Trng hp ngoi l c th c nm (hoc ti nm) trong mt khi catch trong mt
khi try
Mt nguyn tc n gin: Nu bn nm mt ci g , bn phi nm bt n.
Page 82 of 413
To mt kt ni n mt c s d liu MySQL
Trc khi bn c th truy cp d liu trong mt c s d liu, bn phi to ra mt kt ni n
c s d liu.
Trong PHP, iu ny c thc hin vi cc chc nng mysql_connect ().
C php
mysql_connect(servername,username,password);
Thng s
M t
servername
Tn truy nhp
Page 83 of 413
mt khu
Lu : C thm nhiu thng s c sn, nhng nhng ngi c lit k trn l quan trng
nht. y ca chng ti PHP MySQL tham kho bit thm chi tit.
V d
Trong v d sau chng ti lu tr cc kt ni trong mt bin ($ con) cho s dng sau ny
trong kch bn. "Cht" mt phn s c thc hin nu kt ni khng thnh cng:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
?>
Kt thc mt kt ni
Kt ni s c t ng ng khi kch bn kt thc. ng kt ni trc khi s dng
mysql_close () chc nng:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
mysql_close($con);
?>
To mt c s d liu
Cu lnh CREATE DATABASE c s dng to ra mt c s d liu trong MySQL.
C php
CREATE DATABASE database_name
tm hiu thm v SQL, vui lng truy cp ca chng ti hng dn SQL .
Page 84 of 413
V d
V d sau y to ra mt c s d liu gi l "my_db":
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
mysql_close($con);
?>
To mt bng
Cu lnh CREATE TABLE c s dng to ra mt bng trong MySQL.
C php
CREATE TABLE
(
column_name1
column_name2
column_name3
....
)
table_name
data_type,
data_type,
data_type,
V d
V d sau y to ra mt bng c tn l "Ngi", vi ba ct. Cc tn ct s c "FirstName",
"LastName" v "Age":
Page 85 of 413
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
// Create table
mysql_select_db("my_db", $con);
$sql = "CREATE TABLE Persons
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
// Execute query
mysql_query($sql,$con);
mysql_close($con);
?>
Quan trng: Mt c s d liu phi c la chn trc khi mt bng c th c to ra. C
s d liu c chn vi mysql_select_db () chc nng.
Lu : Khi bn to ra mt lnh vc c s d liu kiu varchar, bn phi xc nh di ti a
ca lnh vc ny, v d nh varchar (15).
Cc kiu d liu xc nh kiu d liu ct c th gi. i vi mt ti liu tham kho y ca
tt c cc loi d liu c sn trong MySQL, chng ti hon thnh ti liu tham kho kiu d
liu .
Page 86 of 413
V d
$sql = "CREATE TABLE Persons
(
personID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(personID),
FirstName varchar(15),
LastName varchar(15),
Age int
)";
mysql_query($sql,$con);
C php
C th vit INSERT INTO tuyn b trong hai hnh thc.
Cc hnh thc u tin khng xc nh cc ct d liu s c chn vo, ch c gi tr ca h:
V d
Trong chng trc, chng ta to ra mt bng c tn l "Ngi", vi ba ct "FirstName",
"LastName" v "Age".Chng ti s s dng cng mt bng trong v d ny. V d sau y cho
bit thm hai k lc mi vo bng "Persons":
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
Page 87 of 413
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin',35)");
mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Glenn', 'Quagmire',33)");
mysql_close($con);
?>
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>
</body>
</html>
Khi ngi dng nhp chut vo nt gi dng HTML trong v d trn, cc d liu mu c
gi "insert.php".
Cc tp tin "insert.php" kt ni vi mt c s d liu, v ly cc gi tr t hnh thc vi cc
bin PHP _POST.
Sau , mysql_query () chc nng thc hin cc INSERT INTO tuyn b, v mt k lc mi s
c thm vo bng "Ngi".
y l trang "insert.php":
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
Page 88 of 413
}
mysql_select_db("my_db", $con);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
C php
SELECT column_name(s)
FROM table_name
tm hiu thm v SQL, vui lng truy cp ca chng ti hng dn SQL .
c c PHP thc hin cc tuyn b trn, chng ta phi s dng hm mysql_query
(). Chc nng ny c s dng gi mt truy vn hoc lnh kt ni MySQL.
V d
V d sau y chn tt c cc d liu c lu tr trong bng "Ngi" (k t * chn tt c cc
d liu trong bng):
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
Page 89 of 413
mysql_close($con);
?>
V d trn ca hng d liu tr v bi hm mysql_query () trong bin $ kt qu.
Tip theo, chng ti s dng mysql_fetch_array () chc nng tr li hng u tin t
recordset nh l mt mng. Mi cuc gi n mysql_fetch_array () tr li hng k tip trong
recordset. Cc vng lp trong khi vng qua tt c cc bn ghi trong recordset. in gi tr ca
mi hng, chng ti s dng bin $ row PHP ($ row ['FirstName'] v $ row ['LastName']).
u ra ca cc m trn s l:
Peter Griffin
Glenn Quagmire
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
u ra ca cc m trn s l:
Page 90 of 413
FirstName
Lastname
Glenn
Bai ly
Peter
Mnh WHERE
Mnh WHERE c s dng trch xut ch nhng h s m thc hin mt tiu chun quy
nh.
C php
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
tm hiu thm v SQL, vui lng truy cp ca chng ti hng dn SQL .
c c PHP thc hin cc tuyn b trn, chng ta phi s dng hm mysql_query
(). Chc nng ny c s dng gi mt truy vn hoc lnh kt ni MySQL.
V d
V d sau y chn tt c cc hng t bng "Ngi" "FirstName = 'Peter'":
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons
WHERE FirstName='Peter'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
?>
u ra ca cc m trn s l:
Peter Griffin
ORDER BY T kha
ORDER BY t kha c s dng sp xp d liu trong mt recordset.
Page 91 of 413
C php
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC
tm hiu thm v SQL, vui lng truy cp ca chng ti hng dn SQL .
V d
V d sau y chn tt c cc d liu c lu tr trong bng "Ngi", v sp xp kt qu
theo ct "Age":
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons ORDER BY age");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
echo " " . $row['LastName'];
echo " " . $row['Age'];
echo "<br>";
}
mysql_close($con);
?>
u ra ca cc m trn s l:
Glenn Quagmire 33
Peter Griffin 35
Sp xp theo hai ct
N cng c th t do nhiu hn mt ct. Khi t hng theo nhiu hn mt ct, ct th hai
ch c s dng nu cc gi tr trong ct u tin l bng nhau:
Page 92 of 413
SELECT column_name(s)
FROM table_name
ORDER BY column1, column2
C php
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Lu : Ch mnh WHERE trong c php UPDATE. Mnh WHERE quy nh c th h s
hoc h s cn c cp nht. Nu bn b qua mnh WHERE, tt c h s s c cp
nht!
tm hiu thm v SQL, vui lng truy cp ca chng ti hng dn SQL .
c c PHP thc hin cc tuyn b trn, chng ta phi s dng hm mysql_query
(). Chc nng ny c s dng gi mt truy vn hoc lnh kt ni MySQL.
V d
Trc , trong hng dn, chng ti to ra mt bng c tn l "Ngi". y l n trng nh
th no:
FirstName
LastName
Tui
Peter
35
Glenn
Bai ly
33
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("UPDATE Persons SET Age=36
WHERE FirstName='Peter' AND LastName='Griffin'");
mysql_close($con);
?>
Sau khi cp nht, bng "Ngi" s nh th ny:
Page 93 of 413
FirstName
LastName
Tui
Peter
36
Glenn
Bai ly
33
C php
DELETE FROM table_name
WHERE some_column = some_value
Lu : Ch mnh WHERE trong c php DELETE. Mnh WHERE quy nh c th h s
hoc h s c cn xa. Nu bn b qua mnh WHERE, tt c h s s b xa!
tm hiu thm v SQL, vui lng truy cp ca chng ti hng dn SQL .
c c PHP thc hin cc tuyn b trn, chng ta phi s dng hm mysql_query
(). Chc nng ny c s dng gi mt truy vn hoc lnh kt ni MySQL.
V d
Nhn vo bng sau "Ngi":
FirstName
LastName
Tui
Peter
35
Glenn
Bai ly
33
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("DELETE FROM Persons WHERE LastName='Griffin'");
mysql_close($con);
?>
Sau khi xa, bng s nh th ny:
Page 94 of 413
FirstName
LastName
Tui
Glenn
Bai ly
33
To mt kt ni ODBC
Vi mt kt ni ODBC, bn c th kt ni vo c s d liu no, trn bt k my tnh no
trong mng ca bn, min l c mt kt ni ODBC.
y l cch to ra mt kt ni ODBC mt c s d liu MS Access:
1.
2.
3.
4.
5.
6.
7.
8.
Kt ni n mt ODBC
Odbc_connect () c s dng kt ni vi mt ngun d liu ODBC. Chc nng c bn
thng s: ngun d liu tn, tn ngi dng, mt khu, v con tr mt kiu ty chn.
Odbc_exec () chc nng c s dng thc thi mt cu lnh SQL.
V d
V d sau y to ra mt kt ni n mt DSN gi l northwind, khng c tn ngi dng v
mt khu khng. Sau to ra mt cu lnh SQL v thc hin n:
$conn=odbc_connect('northwind','','');
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
Ly h s
Chc nng odbc_fetch_row () c s dng tr li h s t tp kt qu. Chc nng ny tr
v true nu n c th tr li hng, nu khng sai.
Page 95 of 413
odbc_fetch_row($rs)
Ly Fields t mc k lc
Chc nng odbc_result () c s dng c cc lnh vc t mc k lc. Chc nng ny c
hai tham s: nh danh kt qu ODBC v mt s tn trng.
Cc dng m di y tr v gi tr ca lnh vc u tin t cc h s:
$compname=odbc_result($rs,1);
Cc dng m di y tr v gi tr ca mt lnh vc c gi l "CompanyName":
$compname=odbc_result($rs,"CompanyName");
ng mt kt ni ODBC
Chc nng odbc_close () c s dng ng mt kt ni ODBC.
odbc_close($conn);
V d ODBC
V d sau y cho thy lm th no ln u tin to ra mt kt ni c s d liu, sau
thit lp mt kt qu, v sau hin th cc d liu trong mt bng HTML.
<html>
<body>
<?php
$conn=odbc_connect('northwind','','');
if (!$conn)
{exit("Connection Failed: " . $conn);}
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
if (!$rs)
{exit("Error in SQL");}
echo "<table><tr>";
echo "<th>Companyname</th>";
echo "<th>Contactname</th></tr>";
while (odbc_fetch_row($rs))
{
$compname=odbc_result($rs,"CompanyName");
Page 96 of 413
$conname=odbc_result($rs,"ContactName");
echo "<tr><td>$compname</td>";
echo "<td>$conname</td></tr>";
}
odbc_close($conn);
echo "</table>";
?>
</body>
</html>
XML l g?
XML c s dng m t d liu v tp trung vo d liu l g. Mt tp tin XML m t cu
trc ca d liu.
Trong XML, khng c th c nh ngha trc. Bn phi xc nh cc th ring ca mnh.
Nu bn mun tm hiu thm v XML, vui lng truy cp ca chng ti hng dn XML .
Ngi nc ngoi l g?
c v cp nht - to ra v thao tc mt ti liu XML, bn s cn mt phn tch c php XML.
C hai loi c bn ca phn tch c php XML:
Da trn cy phn tch c php: phn tch c php ny bin i mt ti liu XML vo
mt cu trc cy. N phn tch ton b ti liu, v cung cp truy cp n cc yu t
cy. v d nh Document Object Model (DOM)
Phn tch c php da trn s kin: Xem mt ti liu XML nh l mt lot cc s
kin. Khi mt s kin c th xy ra, n gi mt chc nng x l n
Page 97 of 413
Da trn s kin phn tch c php tp trung vo ni dung ca cc ti liu XML, cu trc ca
chng. Bi v iu ny, phn tch c php da trn s kin c th truy cp d liu nhanh hn
so vi cc phn tch c php da trn cy.
Nhn vo cc phn XML sau y:
<from>Jani</from>
Mt phn tch c php da trn s kin bo co XML trn l mt lot cc ba s kin:
Yu t: t
Bt u CDATA phn gi tr: Jani
ng yu t: t
V d XML trn cha tt c hnh thnh XML. Tuy nhin, v d ny l khng hp l XML, v
khng c nh ngha kiu ti liu (DTD) lin kt vi n.
Tuy nhin, iu ny lm cho khng c s khc bit khi s dng cc phn tch c php nc
ngoi. Ngi nc ngoi l mt phn tch c php khng kim duyt, v b qua bt k cc
DTD.
L mt s kin, khng kim duyt phn tch c php XML, Ngi nc ngoi l nhanh chng
v nh, v mt trn u hon ho cho cc ng dng web PHP.
Lu : cc ti liu XML phi c hnh thnh hoc nc ngoi s to ra mt li.
Ci t
Cc chc nng phn tch c php XML Expat l mt phn ca li PHP. Khng c ci t cn
thit s dng cc chc nng ny.
Mt file XML
Cc tp tin XML di y s c s dng trong v d ca chng ti:
Chng ti mun khi to phn tch c php XML trong PHP, xc nh mt s x l cho cc
s kin khc nhau XML, v sau phn tch cc tp tin XML.
V d
<?php
//Initialize the XML parser
$parser=xml_parser_create();
//Function to use at the start of an element
function start($parser,$element_name,$element_attrs)
{
switch($element_name)
{
case "NOTE":
echo "-- Note --<br>";
break;
case "TO":
echo "To: ";
break;
case "FROM":
echo "From: ";
break;
case "HEADING":
echo "Heading: ";
break;
case "BODY":
echo "Message: ";
}
}
//Function to use at the end of an element
function stop($parser,$element_name)
{
echo "<br>";
}
//Function to use when finding character data
function char($parser,$data)
{
echo $data;
}
//Specify element handler
xml_set_element_handler($parser,"start","stop");
//Specify data handler
xml_set_character_data_handler($parser,"char");
//Open XML file
$fp=fopen("test.xml","r");
//Read data
while ($data=fread($fp,4096))
{
xml_parse($parser,$data,feof($fp)) or
die (sprintf("XML Error: %s at line %d",
Page 99 of 413
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser)));
}
//Free the XML parser
xml_parser_free($parser);
?>
u ra ca cc m trn s l:
DOM l g?
W3C DOM cung cp mt b tiu chun ca cc i tng cho ti liu HTML v XML, v mt
giao din tiu chun cho vic truy cp v thao tc chng. W3C DOM c chia thnh cc phn
khc nhau (Core, XML, HTML) v cc mc khc nhau (DOM Level 1/2 / 3): * Core DOM nh ngha mt tp hp cc i tng cho bt k ti liu c cu trc * XML DOM - nh ngha
mt b tiu chun ca cc i tng cho cc ti liu XML * HTML DOM - nh ngha mt b
tiu chun ca cc i tng cho cc ti liu HTML Nu bn mun tm hiu thm v DOM XML,
vui lng truy cp ca chng ti hng dn XML DOM .
XML Parsing
c v cp nht - to ra v thao tc mt ti liu XML, bn s cn mt phn tch c php XML.
C hai loi c bn ca phn tch c php XML:
Da trn cy phn tch c php: phn tch c php ny bin i mt ti liu XML vo
mt cu trc cy. N phn tch ton b ti liu, v cung cp truy cp n cc yu t
cy
Phn tch c php da trn s kin: Xem mt ti liu XML nh l mt lot cc s
kin. Khi mt s kin c th xy ra, n gi mt chc nng x l n
Ci t
DOM XML chc nng phn tch c php l mt phn ca li PHP. Khng c ci t cn thit
s dng cc chc nng ny.
Mt file XML
Cc tp tin XML di y s c s dng trong v d ca chng ti:
Ti v u ra XML
Chng ti mun khi to phn tch c php XML, ti xml, v u ra n:
V d
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");
print $xmlDoc->saveXML();
?>
u ra ca cc m trn s l:
V d
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");
$x = $xmlDoc->documentElement;
foreach ($x->childNodes AS $item)
{
print $item->nodeName . " = " . $item->nodeValue . "<br>";
}
?>
u ra ca cc m trn s l:
#text =
to = Tove
#text =
from = Jani
#text =
heading = Reminder
#text =
body = Don't forget me this weekend!
#text =
Trong v d trn, bn thy rng c cc nt vn bn trng gia mi phn t.
Khi XML to ra, n thng c mu trng khng gian gia cc nt. XML DOM phn tch c php
x l cc yu t ny l ngi bnh thng, v nu bn khng nhn thc ca h, i khi h gy
ra vn .
Nu bn mun tm hiu thm v XML DOM, vui lng truy cp ca chng ti hng dn XML
DOM .
SimpleXML l g?
SimpleXML l mi trong PHP 5. l mt cch d dng nhn c cc thuc tnh ca mt
nguyn t v vn bn, nu bn bit b tr cc ti liu XML.
So vi DOM hoc phn tch c php nc ngoi, SimpleXML ch mt mt vi dng m c
d liu vn bn t mt phn t.
SimpleXML chuyn i cc ti liu XML vo mt i tng, nh th ny:
SimpleXML l nhanh chng v d dng s dng khi thc hin nhim v c bn nh:
c cc tp tin XML
Nn d liu t chui XML
Chnh sa cc nt vn bn hoc cc thuc tnh
Tuy nhin, khi i ph vi XML tin tin, nh khng gian tn, bn tt hn bng cch s dng
cc phn tch c php nc ngoi hoc DOM XML.
Ci t
PHP 5.0, cc chc nng SimpleXML l mt phn ca li PHP. Khng c ci t cn thit s
dng cc chc nng ny.
S dng SimpleXML
Di y l mt tp tin XML:
Ti cc tp tin XML
Ly tn ca cc yu t u tin
To mt vng lp m s kch hot trn mi nt con, s dng con ci () chc nng
Sn xut cc tn phn t v d liu cho mi nt con
V d
<?php
$xml = simplexml_load_file("test.xml");
echo $xml->getName() . "<br>";
foreach($xml->children() as $child)
{
echo $child->getName() . ": " . $child . "<br>";
}
?>
u ra ca cc m trn s l:
note
to: Tove
from: Jani
heading: Reminder
body: Don't forget me this weekend!
AJAX l g?
AJAX = Asynchronous JavaScript v XML.
AJAX l mt k thut to ra cc trang web nhanh chng v nng ng.
AJAX cho php cc trang web c cp nht khng ng b bng cch trao i mt lng nh
d liu vi my ch ng sau hu trng. iu ny c ngha rng n c th cp nht cc phn
ca mt trang web, m khng cn ti li ton b trang.
Cc trang web c in, (m khng s dng AJAX) phi ti li ton b trang nu cc ni dung
cn thay i.
V d v cc ng dng bng cch s dng AJAX: Google Maps, Gmail, Youtube, v Facebook
tab.
Lm th no AJAX Hot ng
Google Suggest
AJAX c thc hin ph bin vo nm 2005 bi Google, vi Google Suggest.
Google Suggest ang s dng AJAX to ra mt giao din web rt nng ng: Khi bn bt
u g vo hp tm kim ca Google, JavaScript mt gi cc k t vo mt my ch v my
ch tr v mt danh sch gi .
AJAX PHP V d
V d sau y s chng minh lm th no mt trang web c th giao tip vi mt my ch
web trong khi mt ngi s dng loi nhn vt trong mt lnh vc u vo:
V d
Start typing a name in the input field below:
First name:
Suggestions:
<html>
<head>
<script>
function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
M ngun gii thch:
Nu trng u vo l rng (str.length == 0), chc nng xa ni dung gi ch txtHint ra khi
chc nng.
Nu trng u vo khng phi l trng rng, showHint () thc hin cc chc nng sau y:
To mt i tng XMLHttpRequest
To ra cc chc nng c thc hin khi p ng my ch sn sng
Gi yu cu vo mt tp tin trn my ch
Ch rng mt tham s (q) c thm vo URL (vi ni dung ca lnh vc u vo)
File PHP
Cc trang web trn my ch c gi bi JavaScript trn l mt file PHP gi l "gethint.php".
M ngun trong "gethint.php" kim tra mt lot cc tn, v tr v tn tng ng (s) cho trnh
duyt:
<?php
// Fill up array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";
//get the q parameter from URL
$q=$_GET["q"];
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint=="")
{
$hint=$a[$i];
}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}
// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}
//output the response
echo $response;
?>
AJAX C s d liu V d
V d sau y s chng minh lm th no mt trang web c th ly thng tin t mt c s d
liu vi AJAX:
V d
Lois Griff in
FirstName
LastName
Tui
Qu hng
Vic
Peter
41
Quahog
Ch lam ru bia
Lois
40
Newport
Piano Teacher
Swanson
39
Quahog
Glenn
Bai ly
41
Quahog
Phi cng
<html>
<head>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
ShowUser () chc nng no sau y:
File PHP
Cc trang web trn my ch c gi bi JavaScript trn l mt file PHP gi l
"getuser.php".
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ajax_demo", $con);
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Gii thch: Khi truy vn c gi t JavaScript file PHP, sau y xy ra:
1. PHP m mt kt ni n mt my ch MySQL
2. Ngi c tm thy ng
3. Mt bng HTML c to ra, cha y d liu, v gi li cho gi ch "txtHint"
AJAX XML V d
V d sau y s chng minh lm th no mt trang web c th ly thng tin t mt file XML
vi AJAX:
V d
<html>
<head>
<script>
function showCD(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getcd.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
Select a CD:
<select name="cds" onchange="showCD(this.value)">
<option value="">Select a CD:</option>
<option value="Bob Dylan">Bob Dylan</option>
<option value="Bonnie Tyler">Bonnie Tyler</option>
<option value="Dolly Parton">Dolly Parton</option>
</select>
</form>
<div id="txtHint"><b>CD info will be listed here...</b></div>
</body>
</html>
ShowCD () chc nng no sau y:
File PHP
Cc trang web trn my ch c gi bi JavaScript trn l mt file PHP gi l "getcd.php".
Cc kch bn PHP ti mt ti liu XML, " cd_catalog.xml ", chy mt truy vn i vi cc tp
tin XML, v tr v kt qu di dng HTML:
<?php
$q=$_GET["q"];
$xmlDoc = new DOMDocument();
$xmlDoc->load("cd_catalog.xml");
$x=$xmlDoc->getElementsByTagName('ARTIST');
for ($i=0; $i<=$x->length-1; $i++)
{
//Process only element nodes
if ($x->item($i)->nodeType==1)
{
if ($x->item($i)->childNodes->item(0)->nodeValue == $q)
{
$y=($x->item($i)->parentNode);
}
}
}
$cd=($y->childNodes);
for ($i=0;$i<$cd->length;$i++)
{
//Process only element nodes
if ($cd->item($i)->nodeType==1)
{
echo("<b>" . $cd->item($i)->nodeName . ":</b> ");
echo($cd->item($i)->childNodes->item(0)->nodeValue);
echo("<br>");
}
}
?>
Kt qu c hin th khi bn g
Thu hp kt qu nh bn tip tc g
Nu kt qu tr nn qu hp, loi b cc k t nhn thy mt kt qu rng ln hn
<html>
<head>
<script>
function showResult(str)
{
if (str.length==0)
{
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
document.getElementById("livesearch").style.border="1px solid
#A5ACB2";
}
}
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<input type="text" size="30" onkeyup="showResult(this.value)">
<div id="livesearch"></div>
</form>
</body>
</html>
M ngun gii thch:
Nu trng u vo l rng (str.length == 0), chc nng xa ni dung gi ch livesearch v
thot khi chc nng.
Nu trng u vo khng phi l trng rng, showResult () chc nng thc hin nhng iu
sau y:
To mt i tng XMLHttpRequest
To ra cc chc nng c thc hin khi p ng my ch sn sng
Gi yu cu vo mt tp tin trn my ch
Ch rng mt tham s (q) c thm vo URL (vi ni dung ca lnh vc u vo)
File PHP
Cc trang web trn my ch c gi bi JavaScript trn l mt file PHP gi l
"livesearch.php".
M ngun trong "livesearch.php" tm kim mt tp tin XML cho cc chc danh ph hp vi
chui tm kim v tr v kt qu:
<?php
$xmlDoc=new DOMDocument();
$xmlDoc->load("links.xml");
$x=$xmlDoc->getElementsByTagName('link');
<html>
<head>
<script>
function showRSS(str)
{
if (str.length==0)
{
document.getElementById("rssOutput").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("rssOutput").innerHTML=xmlhttp.responseText
;
}
}
xmlhttp.open("GET","getrss.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select onchange="showRSS(this.value)">
<option value="">Select an RSS-feed:</option>
<option value="Google">Google News</option>
<option value="MSNBC">MSNBC News</option>
</select>
</form>
<br>
<div id="rssOutput">RSS-feed will be listed here...</div>
</body>
</html>
Cc showResult () chc nng no sau y:
File PHP
Cc trang web trn my ch c gi bi JavaScript trn l mt tp tin PHP gi l
"getrss.php":
<?php
//get the q parameter from URL
$q=$_GET["q"];
//find out which feed was selected
if($q=="Google")
{
$xml=("http://news.google.com/news?ned=us&topic=h&output=rss");
}
elseif($q=="MSNBC")
{
$xml=("http://rss.msnbc.msn.com/id/3032091/device/rss/rss.xml");
}
$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);
//get elements from "<channel>"
$channel=$xmlDoc->getElementsByTagName('channel')->item(0);
$channel_title = $channel->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$channel_link = $channel->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$channel_desc = $channel->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;
<html>
<head>
<script>
function getVote(int)
{
if (window.XMLHttpRequest)
To mt i tng XMLHttpRequest
To ra cc chc nng c thc hin khi p ng my ch sn sng
Gi yu cu vo mt tp tin trn my ch
Ch rng mt tham s (vote) c thm vo URL (vi gi tr c hoc khng c ty
chn)
File PHP
Cc trang web trn my ch c gi bi JavaScript trn l mt tp tin PHP gi l
"poll_vote.php":
<?php
$vote = $_REQUEST['vote'];
Text File
Cc tp tin vn bn (poll_result.txt) l ni chng ti lu tr cc d liu t cc cuc thm d.
N c lu tr nh th ny:
0||0
S u tin i din cho "Yes" phiu, s th hai i din cho phiu "Khng".
Lu : nh cho php my ch web ca bn chnh sa cc tp tin vn bn. Cung cp cho
truy cp tt c mi ngi, ch cn cc my ch web (PHP).
Chapter Ngoi : Bi Tp
Bi 11: Vit ng dng ng nhp bng PHP v
MYSQL
nhng bi trc chng ta hc qua cc kin thc trng yu v
PHP. Tuy nhin, c th xy dng mt website hon chnh
bng nhng kin thc th qu tht khng n gin. Bi v cc
kin thc qua sch v v ti liu d sao cng ch l nhng kin
thc tng qut v thiu tnh khch quan thc tin. Nn khi ngi
hc lp trnh bc vo giai on vit ng dng th thng rt lng tng. cng l l do
ti vit bi ny hng dn cc bn dn lm quen vi cch tip cn mt ng dng PHP
v MYSQL nh th no.
on code trn s kim tra xem ngi dng c tin hnh nhn nt ng nhp hay
khng. V nu c th chng ta s xt tip tnh trng ngi dng c trng cc
username v password hay khng. Nu c chng ta s thng bo li bn trn form,
ngi s dng tin hnh nhp liu. V phin bn PHP 5.3 tr ln s yu cu ta khai bo
bin trc khi s dng. V th mc nh ban u ta khi to 2 bin $u v $p mang gi tr
l rng.
K n chng ta kim tra xem c tn ti hai bin $u v $p (ch khi ngi dng ng nhp
thnh cng th mi c th to ra 2 bin ). Tip n chng ta tin hnh kt ni c s d
liu (xem li bi kt hp PHP & MYSQL trong ng dng web).
1 <?php
$conn=mysql_connect("localhost","root","root") or die("can't connect
2
this database");
3 mysql_select_db("project",$conn);
4 ?>
V tin hnh kim tra xem username v password ngi s dng va nhp c trng khp
vi thng tin c trong c s d liu hay khng ?. Nu khng th chng ta s bo li ngay.
Ngc li s tin hnh ly d liu t bng v gn vo session. c th qun l phin
lm vic mt cch hiu qu trn mi trang ca khu vc admin (xem li bi khi nim c
bn v cookie v session).
01 <?php
02 if($u && $p)
03 {
04
05 mysql_select_db("project",$conn);
$sql="select * from user where username='".$u."' and
06
password='".$p."'";
07 $query=mysql_query($sql);
08 if(mysql_num_rows($query) == 0)
09 {
10
echo "Username or password is not correct, please try again";
11 }
12 else
13 {
14
$row=mysql_fetch_array($query);
15
16
session_start();
$_SESSION['userid'] = $row['id'];
17
$_SESSION['level'] = $row['level'];
18 }
19 }
20 ?>
04 $u=$p="";
05 if($_POST['username'] == NULL)
06 {
07
echo "Please enter your username<br />";
08 }
09 else
10 {
11
$u=$_POST['username'];
12 }
13 if($_POST['password'] == NULL)
14 {
15
echo "Please enter your password<br />";
16 }
17 else
18 {
19
$p=$_POST['password'];
20 }
21 if($u && $p)
22 {
$conn=mysql_connect("localhost","root","root") or die("can't
connect this database");
24
mysql_select_db("project",$conn);
23
27
28
if(mysql_num_rows($query) == 0)
{
29
30
31
32
else
{
33
34
$row=mysql_fetch_array($query);
session_start();
35
36
$_SESSION['userid'] = $row[id];
$_SESSION['level'] = $row[level];
37
38
39 }
40 }
41 ?>
42 <form action='login.php' method='post'>
43 Username: <input type='text' name='username' size='25' /><br />
44 Password: <input type='password' name='password' size='25' /><br />
bi sau, chng ta s tip tc tm hiu ng dng kt hp PHP & MYSQL cho vic
thm mt thnh vin nh th no. Mi s gp , cng nh thc mc ca cc bn dnh
cho bi vit vui lng s dng tnh nng tho lun ti din n. Hoc thng qua vic lin
h ca h thng website. Mong s nhn c nhiu kin ng gp t cc bn.
Sau khi ng nhp vo trang admin ngi dng s c y sang trang qun l admin, ti
y ch nhng ai ng nhp ng vi username v password trong c s d liu v c
quyn hn level l 2 th mi c th truy xut vo trang ny. V vy chng ta cn thao tc
kim tra session qun l phin lm vic ca ngi s dng. t on code sau
nhng trang bn mun kim tra quyn truy cp ca ngi s dng.
01 <?php
02 session_start();
03 if(isset($_SESSION['userid']) && $_SESSION['level'] == 2)
04 {
05 // ti y thc thi cc hot ng khi ng nhp thnh cng.
06 }
07 else
08 {
09 header("location: login.php");
10 exit();
11 }
12 ?>
Tng t nh nhng bi trc, chng ta cng ln lt kim tra tng i tng. Trc ht
cn xem th ngi dng nhn nt Add New user cha ?, sau li khai bo 2 bin $u
v $p, mc nh ban u ta cho 2 bin ny l rng. K ti ta kim tra xem ngi dng
nhp y thng tin cha. Cui cng l so snh gia password v re-password c ging
nhau hay khng. Tip theo chng ta gn bin $l s bng vi gi tr m khi ngi dng
chn level cho user . (xem li Bi 4: X l gi tr form trong PHP)
01 <?php
02 if(isset($_POST['adduser']))
03 {
04 $u=$p="";
05 if($_POST['username'] == NULL)
06 {
07
echo "Vui long nhap username<br />";
08 }
09 else
10 {
11
$u=$_POST['username'];
12 }
13 if($_POST['password'] != $_POST['re-password'])
14 {
15
echo "Password va re-password khong chinh xac<br />";
16 }
17 else
18 {
19
20
if($_POST['password'] == NULL )
{
21
22
23
24
else
{
25
26
$p=$_POST['password'];
}
27 }
28 $l=$_POST['level'];
29 }
30 ?>
K n chng ta li tip tc kim tra xem c tn ti bin $u, $p v $l hay khng (ch khi
ngi dng nhp liu th mi tn ti cng lc 3 bin ny). sau khi kim tra s tn ti
ca 3 bin ny chng ta tip tc dng PHP kt ni c s d liu kim tra xem
username m ngi dng va chn c trng vi username khc trong c s d liu cha.
nu trng th phi xut thng bo li yu cu h chn username khc cn nu khng th ta
li tin hnh thm thnh vin mi ny vo CSDL.
01 <?php
02 if($u & $p & $l)
03 {
04
05 mysql_select_db("project",$conn);
06 $sql="select * from user where username='".$u."'";
07 $query=mysql_query($sql);
08 if(mysql_num_rows($query) != "" )
09 {
10
echo "Username nay da ton tai roi<br />";
11 }
12 else
13 {
14
15
16
$query2=mysql_query($sql2);
echo "Da them thanh vien moi thanh cong";
17 }
18 }
19 ?>
11
12
}
else
13
14
15
16
}
if($_POST['password'] != $_POST['re-password'])
17
18
19
20
}
else
21
22
$u=$_POST['username'];
if($_POST['password'] == NULL)
23
24
25
26
}
else
27
28
29
30
}
}
31
32
$l=$_POST['level'];
if($u & $p & $l)
33
34
$p=$_POST['password'];
$conn=mysql_connect("localhost","root","root") or die("can't
connect this database");
35
36
mysql_select_db("project",$conn);
$sql="select * from user where username='".$u."'";
37
38
$query=mysql_query($sql);
if(mysql_num_rows($query) != "" )
39
40
41
42
}
else
43
44
45
46
47
48
$query2=mysql_query($sql2);
echo "Da them thanh vien moi thanh cong";
}
}
49 }
50 }
51 ?>
52 <form action='add_user.php' method='POST'>
53 Level: <select name='level'>
54 <option value='1'>Member</option>
55 <option value='2'>Admin </option>
56 </select><br />
57 Username: <input type='text' name='username' size='25' /><br />
58 Password: <input type='password' name='password' size='25' /> <br />
Re-Password: <input type='password' name='re-password' size='25' /><br
/>
60 <input type='submit' name='adduser' value='Add New User' />
59
61 </form>
62 <?php
63 }
64 else
65 {
66 header("location: login.php");
67 exit();
68 }
69 ?>
dng qun tr cc ti khon. Hay ni cch khc l h thng li ton b danh sch ca
nhng thnh vin trn website ca chng ta.
Sau khi ng nhp vo trang admin ngi dng s c y sang trang qun l admin, ti
y ch nhng ai ng nhp ng vi username v password trong c s d liu v c
quyn hn level l 2 th mi c th truy xut vo trang ny. V vy chng ta cn thao tc
kim tra session qun l phin lm vic ca ngi s dng. t on code sau
nhng trang bn mun kim tra quyn truy cp ca ngi s dng.
01 <?php
02 sessison_start();
03 if(isset($_SESSION['userid']) && $_SESSION['level'] == 2)
04 {
05 // ti y thc thi cc hot ng khi ng nhp thnh cng.
06 }
07 else
08 {
09 header("location: login.php");
10 exit();
11 }
12 ?>
this database");
03 mysql_select_db("project",$conn);
04 $sql="select * from user order by id DESC";
05 $query=mysql_query($sql);
06 if(mysql_num_rows($query) == "")
07 {
echo "<tr><td colspan='5' align='center'>Chua co username
08
nao</td></tr>";
09 }
10 ?>
on code trn tin hnh la chn tt c user c trong database. ng thi kim tra
xem trong database c tn ti user no khng. Nu khng s xut ra thng bo "cha c
username no". Ngc li khi c tn ti user chng ta s x l tip nh sau:
01 <?php
02 $stt=0;
03 while($row=mysql_fetch_array($query))
04 {
05 $stt++;
06 echo "<tr>";
07 echo "<td>$stt</td>";
08 echo "<td>$row['username']</td>";
09 if($row['level'] == "1")
10 {
11 echo "<td>Member</td>";
12 }
13 else
14 {
15 echo "<td>Admin</td>";
16 }
17 echo "<td><a href='edit_user.php?userid=$row[id]'>Edit</a></td>";
18 echo "<td><a href='del_user.php?userid=$row[id]'>Del</a></td>";
19 echo "</tr>";
20 ?>
28 $stt++;
29 echo "<tr>";
30 echo "<td>$stt</td>";
31 echo "<td>$row['username']</td>";
32 if($row['level'] == "1")
33 {
34 echo "<td>Member</td>";
35 }
36 else
37 {
38 echo "<td>Admin</td>";
39 }
40 echo "<td><a href='edit_user.php?userid=$row[id]'>Edit</a></td>";
41 echo "<td><a href='del_user.php?userid=$row[id]'>Del</a></td>";
42 echo "</tr>";
43 }
44
45 }
46 ?>
47 </table>
01 <?php
02 sessison_start();
03 if(isset($_SESSION['userid']) && $_SESSION['level'] == 2)
04 {
05 // ti y thc thi cc hot ng khi ng nhp thnh cng.
06 }
07 else
08 {
09 header("location: login.php");
10 exit();
11 }
12 ?>
Vy ta c.
01 <?php
02 $sql="select * from user where id='".$id."'";
03 $query=mysql_query($sql);
04 $row=mysql_fetch_array($query);
05 ?>
Tip ti ngi dng s nhn nt edit. Vic cn li ca chng ta l kim tra d liu khi h
tin hnh chnh sa d liu. im khc bit y l chng ta phi cn nhc khi vit trang
chnh sa. Bi khng phi ai vo chnh sa cng u sa c thng tin username,
password, level. C khi h ch sa mi level hoc c khi h ch sa mi password.
Ta kim tra password v repassword c ging nhau hay khng ?. Nu chng khc nhau
ngha l ngi dng nhp liu nhng nhp sai. Vy phi cnh bo li cho h bit l h
nhp sai. Cn ngc li nu password v repassword ging nhau th s ny sinh 2 trng
hp con.
Khi trng hp con 1 chng ta s khi to bin $p v ghi nhn thng tin h nhp
liu. V trng hp 2 chng ta khng ghi nhn thng tin ngi nhp liu v h khng
c nh chnh sa mt khu. C th vit on code n gin nh sau:
01 <?php
02 if($_POST['pass'] != $_POST['repass'])
03 {
04 echo "Password and re-password is not correct";
05 }
06 else
07 {
08 if($_POST['pass'] != NULL)
09 {
10
$p=$_POST['pass'];
11 }
12 }
13 ?>
05 mysql_query($sql);
06 header("location:mana_user.php");
07 exit();
08 }
09 else
10 {
11 if($u && $l)
12 {
$sql="update user set username='".$u."', level='".$l."' where
id='".$id."'";
14
mysql_query($sql);
13
15
16
header("location:mana_user.php");
exit();
17 }
18 }
19 ?>
Sau khi sa thnh cng mt thnh vin chng ta s a ngi dng tr v vi trang qun
l (xem bi 13 bit cch xy dng trang qun l thnh vin nh th no)
11 else
12 {
13
$u=$_POST['user'];
14 }
15 if($_POST['pass'] != $_POST['repass'])
16 {
17
echo "Password and re-password is not correct";
18 }
19 else
20 {
21
22
if($_POST['pass'] != NULL)
{
23
24
$p=$_POST['pass'];
}
25 }
26 $l = $_POST['level'];
27 if($u && $p && $l )
28 {
$sql="update user set username='".$u."', password='".$p."',
level='".$l."' where id='".$id."'";
30
mysql_query($sql);
29
31
32
header("location:mana_user.php");
exit();
33 }
34 else
35 {
36
if($u && $l)
37
38
{
$sql="update user set username='".$u."', level='".$l."' where
id='".$id."'";
39
40
mysql_query($sql);
header("location:mana_user.php");
41
42
exit();
}
43 }
44 }
45 $sql="select * from user where id='".$id."'";
46 $query=mysql_query($sql);
47 $row=mysql_fetch_array($query);
48 ?>
49 <form action="edit_user.php?userid=<?=$id?>" method=post>
50 Level: <select name=level>
51 <option value=1 <? if($row[level] == 1) echo "selected"; ?>)
>Member</option>
<option value=2 <? if($row[level] == 2) echo "selected";
52
?>>Administrator</option>
53 </select><br />
Username: <input type=text name=user size=20
54
value="<?=$row[username]?>" /><br />
55 Password: <input type=password name=pass size=20 /> <br />
56 Re-password: <input type=password name=repass size=20 /><br />
57 <input type=submit name=ok value="Edit User" />
58 </form>
Sau khi xa xong thnh vin th h thng s a chng ta tr v trang qun l user li.
C- Tng kt:
Nh vy chng ta kt thc cc thao tc thm, sa, xa, qun l thnh vin. Qua nhng
chui bi hc ny, chc hn cc bn c nhng khi nim hnh thnh t vic ng dng
lp trnh PHP xy dng cc h thng c bn ri. Vic lp trnh 1 ng dng i hi bn
ngoi vic vn dng ni dung hc ra, bn cn phi bit linh ng x l cc tnh hung
mt cch hiu qu. Trnh vic rp khun mt cch my mc v hc thuc cc ni dung
code. V nhng m hnh khc, bi ton khc bn s c nhng cch thc x l v gii
quyt khc nhau.
Mi s gp , cng nh thc mc ca cc bn dnh cho bi vit vui lng s dng tnh
nng tho lun ti din n. Hoc thng qua vic lin h ca h thng website. Mong
s nhn c nhiu kin ng gp t cc bn.
Trc tin, chng ta tin hnh to form HTML n gin thc thi thao tc nhp liu
nh sau:
01 <form action="form.php" method=post>
02 <table>
03 <tr>
04
<td align="left">
05
06
<label for="captcha">Captcha</label>
</td>
07
08
<td>
<input type="text" name="txtCaptcha" maxlength="10" size="32" />
09
10
</td>
<td>
11
12
13 </tr>
14 <tr>
15
16
<td> </td>
<td>
17
18
19 </tr>
20 </table>
21 </form>
Tip tc, trong trang form chng ta phi khi to session chng nhn c cc gi tr
m ta khi to v s dng trang random_image, k ti ta kim tra xem ngi dng
c nhn submit cha. Nu c ta s tip tc kim tra xem ngi dng nhp vo textbox c
ng l dy s hin th trn hnh nh hay khng. V xut ra thng bo tng ng vi ni
dung ca ngi nhp liu. (xem li bi 4: X l gi tr form trong PHP)
if($_POST['txtCaptcha'] == $_SESSION['security_code'])
{
13
14
15
16
else
{
17
18
19 }
20 }
21 ?>
22 <form action="form.php" method=post>
23 <table>
24 <tr>
25
26
<td align="left">
<label for="captcha">Captcha</label>
27
28
</td>
<td>
29
30
31
32
<td>
<img src="random_image.php" />
33
</td>
34 </tr>
35 <tr>
36
<td> </td>
37
38
<td>
<input type=submit name=ok value="Check" />
39
</td>
40 </tr>
41 </table>
42 </form>
Tng kt:
Khi ngi dng truy cp vo trang web, chng ta s tin hnh insert thng tin ca h vo
c s d liu vi cc tham s c bn nhng trong database.
Sau ta tin hnh ghi nhn thng tin ngi dng vo CSDL.
1 <?php
$sql="insert into useronline(tgtmp,ip,local)
2
values('$tg','$REMOTE_ADDR','$PHP_SELF')";
3 $query=mysql_query($sql);
4 ?>
Tip n ta tin hnh xa record khi thi gian thc ln hn thi gian trong c s d liu.
1 <?php
2 $sql="delete from useronline where tgtmp < $tgnew";
3 $query=mysql_query($sql);
4 ?>
Tip tc l cng vic hin th thng tin ra bn ngoi bng cch lit k cc record c trong
database.
1 <?php
2 $sql="SELECT DISTINCT ip FROM useronline WHERE local='$PHP_SELF'";
3 $query=mysql_query($sql);
4 $user = mysql_num_rows($query);
5 ?>
DISTINCT l c php cho php lit k cc dng record m khng cho php chng c d
liu trng lp nh c php select bnh thng.
Phn vic cui cng cn li l chng ta s xut thng tin y ra trnh duyt.
1 Cu hi c nhiu cu tr li.
Bng cu tr li (anwser)
1 mysql> create table answer(aid INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
2 -> qid INT(10) UNSIGNED NOT NULL,
3 -> atitle VARCHAR(255) NOT NULL,
4 -> acount INT(10) NOT NULL DEFAULT '0',
5 -> PRIMARY KEY(aid));
Nhp liu bng CSDL ta c:
mysql> Insert into question(qtitle,qdate) values("Ban thay qhonline the
nao ?","
2 2009-10-10");
Kt ni c s d liu:
1 <?php
$conn=mysql_connect("localhost","root","root") or die("can not connect
2
database");
3 mysql_select_db("poll_exam",$conn);
4 ?>
17 }
18 echo "<input type='submit' name='ok' value='Binh Chon'>";
19 echo "<a href='result.php?questionid=$qid'>Xem Ket Qua</a>";
20 echo "</form>";
21 }
22 ?>
V khi ngi dng nht nt Bnh chn, chng ta s gi li chnh trang x l d liu
m ngi dng va la chn.
Vy ta phi s dng lnh isset() kim tra xem ngi dng c nhn nt bnh chn
khng, tip n ta ly ra id m ngi dng va tin hnh chn form bn di.
Cui cng ta cp nht d liu bng cch ly s trong c s d liu cng tip cho 1 n v
na. V a ngi dng sang trang kt qu.
22 $query2=mysql_query($sql2);
23 if(mysql_num_rows($query2) > 0)
24 {
25
while($row2=mysql_fetch_array($query2)){
echo "<input type=radio name=answer
26
value=$row2[aid]>$row2[atitle]<br />";
27
}
28 }
29 echo "<input type='submit' name='ok' value='Binh Chon'>";
30 echo "<a href='result.php?questionid=$qid'>Xem Ket Qua</a>";
31 echo "</form>";
32 }
33 ?>
u tin, ta ly gi tr t poll.php?questionid=1. vy 1 l gi tr ta s c c t
$_GET['questionid']. Tip n ta li dng gi tr va ly c ny lit k thng tin cu
hi v tnh ton gi tr.
tnh ton gi tr, ta cn bit tng s bnh chn trong ton b cc cu tr li hin nay l
bao nhiu. Bng cu lnh SUM ta c th lm c iu .
1
1 <?php
$sql2="select qid, SUM(acount) as total from answer group by qid
2
having qid='".$qid."'";
3 $query2=mysql_query($sql2);
4 $row2=mysql_fetch_array($query2);
5 $total=$row2[total];
6 ?>
10 }
11 ?>
13 $row2=mysql_fetch_array($query2);
14 $total=$row2[total];
15 $sql3="select * from answer where qid='".$qid."' order by aid";
16 $query3=mysql_query($sql3);
17 if(mysql_num_rows($query3) > 0){
18
while($row3=mysql_fetch_array($query3)){
19
$percent=round(($row3[acount]/$total)*100,2);
echo "<h4 style='color:red; font:12px verdana; '>$row3[atitle] :
20
$row3[acount] ($percent %)</h4>";
21
}
22 }
23 }
24 ?>
Sau khi ngi dng nhn nt accept th cng l lc chng ta to ra s field upload theo
yu cu ca h. Vy, ta c code x l bn di nh sau: (xem li bi 4: x l gi tr trn
form).
01 <?php
02 if(isset($_POST['ok_num']))
03 {
04
$num=$_POST['txtnum'];
05
06
09
10
{
echo "<input type='file' name='img[]' /><br />";
11
}
echo "<input type='submit' name='ok_upload'
12
value='Upload' />";
13
14 }
echo "</form>";
15 ?>
$num=$_POST['txtnum'];
09
10
13
14
{
echo "<input type='file' name='img[]' /><br />";
15
}
echo "<input type='submit' name='ok_upload'
16
value='Upload' />";
17
18 }
echo "</form>";
19 ?>
Ti trang thc hin nhim v doupload.php ta cn kim tra xem, ngi dng c nhn nt
upload t trang bn kia hay khng ?. Nu c ta s x l cng on upload y, nu khng
ta cn thng bo li cho ngi dng v yu cu h chn file.
01 <<?php
02 if(isset($_POST['ok_upload']))
03 {
04
05 }
06 else
07 {
08
echo "Vui long chon hinh truoc khi truy cap vao trang nay";
09 }
10 ?>
Nh vy, khi ngi dng nhn upload, ta s ly c tham s l bin $num t lin kt
$_GET[file'] m ta thit lp trn phn form action ca file upload trang trc.
Bin $num ny dng thc thi vic upload v tun t ly cc thng tin ca file.
upload file t my ln h thng ta cn s dng hm:
move_uploaded_file(tn_file_tm,ng dn ti h thng).
C th din gii nm na cng vic ca hm ny nh sau: Ngay sau khi ngi dng nhn
upload, h thng s to ra 5 tham s ng vi tng file. C th l tn tm (tmp_name), tn
gc (name), kch thc (size), nh dng mime (type) v li (error) nu c. V khc vi
kiu nhp liu thng thng, khi chng ta s dng <input type=file name=ten> th lc
ny s pht sinh mt bin mi trng mi l $_FILES[ten'] v d nhin n s i km vi
5 tham s c th trn.
V d: $_FILES[ten'][name'] //Ly ra tn gc ca file.
Vy ng vi c php upload trn ta s c:
move_uploaded_file($_FILES['img']['tmp_name'],"data/".$_FILES['img']['name']);
C php ny s t ng upload hnh nh ln th mc data trn h thng. Vy ta cn phi
to th mc data ngang cp vi 2 file upload v doupload. Nu l host tht, bn cn
CHMOD th mc l 777 (cho php th mc c ton quyn) th mi thc thi upload file
c.
Trong tnh hung ca chng ta, v l upload mt lc nhiu file, nn lc ny ta phi s
dng tham s mng ti trang upload ta khi to.
Vy ng vi bin $num ta nhn t upload trn ta s trin khai code n gin nh sau:
1 <?php
2 for($i=0; $i< $num; $i++)
3
{
move_uploaded_file($_FILES['img']['tmp_name'][$i],"data/".$_FILES['im
4
g']['name'][$i]);
5 $url="data/".$_FILES['img']['name'][$i];
6 $name=$_FILES['img']['name'][$i];
7}
8 ?>
Nh vy mi khi upload thnh cng mt hnh nh, ta phi thm hnh nh vo CSDL
nh sau:
1 <?php
2 $sql="insert into images(img_url,img_name) values('$url','$name')";
3 mysql_query($sql);
4 ?>
Sau khi thm vo CSDL ta cn hin th thng tin v hnh nh va upload cho ngi
dng bit h upload thnh cng.
Khi ta s dng mt bin $site lu ng dn gc hin th trn textbox.
$name=$_FILES['img']['name'][$i];
$sql="insert into images(img_url,img_name) values('$url','$name')";
15
16
mysql_query($sql);
echo "Upload Thanh cong file <b>$name</b><br />";
17
18
21 mysql_close($conn);
22 }
23 else
24 {
25 echo "Vui long chon hinh truoc khi truy cap vao trang nay";
26 }
27 ?>
7 );
Sau khi hon tt vic chun b c s d liu v giao din, tip theo ta s xy dng
trang hin th cc mn hng trn website, cho php ngi s dng la chn sch khi truy
cp.
lit k danh sch cc quyn sch ang c trong database, ta cn kt ni CSDL vi
thao tc code nh sau. (xem li bi 10: kt hp php & mysql trong ng dng website).
1 <?php
2 $connect=mysql_connect("localhost","root","root")
3 or die("Can not connect database");
4 mysql_select_db("shop",$connect);
5 ?>
03 $query=mysql_query($sql);
04 if(mysql_num_rows($query) > 0)
05 {
06 while($row=mysql_fetch_array($query))
07 {
08
echo "<div class='pro'>";
09
echo "<h3>$row[title]</h3>";
echo "Tac Gia: $row[author] - Gia: ".number_format($row[price],3)."
10
VND<br />";
echo "<p align='right'><a href='addcart.php?item=$row[id]'>Mua Sach
Nay</a></p>";
12
echo "</div>";
11
13 }
14 }
15 ?>
on code trn thc thi vic hin th sch nu trong CSDL t nht 1 record. V chng
s lit k tiu sch, tc gi, gi tin. y, ti s dng number_format() ly ra 3 s
000 cui, ng vi n v tin t ca Vit Nam l VN.
Sau cng ti to mt lin kt cho php thm quyn sch vo gi hng nu ngi mua
cm thy ng . (addcart.php s l trang thm vo gi hng vi tham s l m ca quyn
sch).
Ni n ng dng shopping cart th hin nay, trn th trng tn ti nhiu phng php
code. C th s dng chui lu gi hng, cng c th lu vo CSDL nhp gi hng
ca ngi dng v cng c th s dng mng v session lu thng tin gi hng. Trong
khun kh bi vit ny, ti s s dng session v mng lu thng tin gi hng. (xem
li Bi 7: Khi nim c bn v Cookie v session trong PHP)
Vy trc khi cho hin th gi hng, ta cn kim tra xem c tn ti id no trong gi hng
hay khng. V v id lu dng mng a chiu, nn ta cn dng vng lp duyt mng
foreach.
foreach($_SESSION[cart'] as $k=>$v)
Vi $k c ngha tng ng $id quyn sch v $v tng ng l s lng ca quyn
sch trong gi hng. Vy nu tn ti bin $k, th tc c ngha l trong gi hng c sch.
Khi ta s dng mt bin bo hiu rng sch c tn ti trong gi hng hay khng.
01 <?php
02 $ok=1;
03 if(isset($_SESSION['cart']))
04 {
05
06
foreach($_SESSION['cart'] as $k=>$v)
{
07
08
if(isset($k))
{
09
10
$ok=2;
}
11
}
12 }
13 if ($ok != 2)
14
{
15
echo '<p>Ban khong co mon hang nao trong gio hang</p>';
16 } else {
17
$items = $_SESSION['cart'];
echo '<p>Ban dang co <a href="cart.php">'.count($items).' mon hang
18
trong gio hang</a></p>';
19 }
20 ?>
Trong on code trn ta s dng hm count nhm m xem trong mng hin ti (gi
hng) hin ang c bao nhiu quyn sch. V thc thi vic bo cho ngi dng bit h
ang c bao nhiu quyn sch trong gi hng.
Ton b code x l ca trang mua sch (index.php) ny nh sau:
01 <?php
02 session_start();
03 ?>
04 <html>
05 <head>
06 <title>Demo Shopping Cart - Created By My Kenny</title>
07 <link rel="stylesheet" href="style.css" />
08 </head>
09 <body>
{
if(isset($v))
19
20
21
22
{
$ok=2;
}
}
23 }
24 if ($ok != 2)
25
26
{
echo '<p>Ban khong co mon hang nao trong gio hang</p>';
27 } else {
28
$items = $_SESSION['cart'];
echo '<p>Ban dang co <a href="cart.php">'.count($items).' mon hang
trong gio hang</a></p>';
30 }
29
31 ?>
32 </div>
33 <?php
34 $connect=mysql_connect("localhost","root","root")
35 or die("Can not connect database");
36 mysql_select_db("shop",$connect);
37 $sql="select * from books order by id desc";
38 $query=mysql_query($sql);
39 if(mysql_num_rows($query) > 0)
40 {
41 while($row=mysql_fetch_array($query))
42 {
43
44
47
echo "</div>";
48 }
49 }
50
51 ?>
52 </body>
53 </html>
Nh vy, trong bi ny chng ta hon tt trang xem sch v trang x l vic thm sn
phm mi vo gi hng nh th no. Mi cc bn c tip bi sau vi tnh nng qun l,
sa, xa tng mn hng hoc c gi hng trong h thng.
3 $query=mysql_query($sql);
4 while($row=mysql_fetch_array($query))
5 ?>
Tip tc, ta lp ton b thng tin sch bao gm tn, tc gi, gi tin v c s lng m ta
lu trong session l $_SESSION['cart'][ 'ID_Mn_Hng']. ID_Mn_hng chnh l
thng tin ta lp ra t CSDL ($row[id]).
Bn cnh ti phn s lng, ta s a gi tr lu session ra textbox (v ti gi hng,
ngi dng c php iu chnh s lng, nn lc ny ta cn to textbox cho h iu
chnh). V lp ton b cc quyn sch nn ti tn tn ca textbox s lng ta cng cn
truyn id nhn bit s lng thuc ID ca quyn sch no.
1 <?php
echo "<p align='right'>So Luong: <input type='text'
2 name='qty[$row[id]]' size='5' value='{$_SESSION['cart'][$row[id]]}' />
- ";
3 ?>
Sau cng, ta cn tnh tng tin ca ton b sn phm c trong gi hng. Bng cch cng
dn tng gi tin ca tng mn.
1 <?php
2 $total+=$_SESSION['cart'][$row[id]]*$row[price];
3 ?>
ng thi, ta cng to nt cho php ngi dng cp nht. V cho php ngi dng xa
ton b gi hng.
1 <?php
echo "<input type='submit' name='submit' value='Cap Nhat Gio Hang'
2
/>";
Nh vy, code y s l:
01 <?php
02 echo "<form action='cart.php' method='post'>";
03 foreach($_SESSION['cart'] as $key=>$value)
04 {
05 $item[]=$key;
06 }
07 $str=implode(",",$item);
$connect=mysql_connect("localhost","root","root") or die("Can not
08
connect database");
09 mysql_select_db("shop",$connect);
10 $sql="select * from books where id in ($str)";
11 $query=mysql_query($sql);
12 while($row=mysql_fetch_array($query))
13 {
14 echo "<div class='pro'>";
15 echo "<h3>$row[title]</h3>";
echo "Tac gia: $row[author] - Gia: ".number_format($row[price],3)."
16
VND<br />";
echo "<p align='right'>So Luong: <input type='text'
17 name='qty[$row[id]]' size='5' value='{$_SESSION['cart'][$row[id]]}'>
- ";
echo "<a href='delcart.php?productid=$row[id]'>Xoa Sach
18
Nay</a></p>";
echo "<p align='right'> Gia tien cho mon hang: ".
number_format($_SESSION['cart'][$row[id]]*$row[price],3) ." VND</p>";
20 echo "</div>";
19
21 $total+=$_SESSION['cart'][$row[id]]*$row[price];
22 }
23 echo "<div class='pro' align='right'>";
echo "<b>Tong tien cho cac mon hang: <font color='red'>".
24
number_format($total,3)." VND</font></b>";
25 echo "</div>";
echo "<input type='submit' name='submit' value='Cap Nhat Gio Hang'
26
/>";
27 echo "<div class='pro' align='center'>";
echo "<b><a href='index.php'>Mua Sach Tiep</a> - <a
28
href='delcart.php?productid=0'>Xoa Bo Gio Hang</a></b>";
29 echo "</div>";
30 ?>
Sau khi thit lp thnh cng trang gi hng c bn, lc ny ta c th thm sch mt
cch d dng. Tuy nhin, gi s trong trng hp khng c sch th sao ?. Chng ta vn
cha xt n trng hp gi hng rng th s nh th no. Vy khi no th gi hng rng
?. l khi session ca gi hng khng tn ti Id ca quyn sch no. C th,
$_SESSION[cart'][id]. Khi id khng tn ti trong session ny th cng l lc gi hng
khng tn ti.
Vy trc khi cho hin th gi hng, ta cn kim tra xem c tn ti id no trong gi hng
hay khng. V v id lu dng mng a chiu, nn ta cn dng vng lp duyt mng
foreach.
foreach($_SESSION[cart] as $k=>$v)
Vi $k c ngha tng ng $id quyn sch v $v tng ng l s lng ca quyn
sch trong gi hng. Vy nu tn ti bin $k, th tc c ngha l trong gi hng c sch.
01 <?php
02 $ok=1;
03 if(isset($_SESSION['cart']))
04 {
05 foreach($_SESSION['cart'] as $k => $v)
06 {
07
if(isset($k))
08
09
10
{
$ok=2;
}
11 }
12 }
13 if($ok == 2)
14 {
15 // code x l gi hng trn.
16 }
17 ?>
on code ny, ta s dng bin $ok lm bin kim tra, mc nh khi load d liu bin
$ok s bng 1. V khi trong gi hng tn ti sch th chng ta s thay i bin $ok thnh
2. V gi gi hng nh code trn.
phn trn, ta cng c cp khi ngi dng tin hnh chnh sa s lng tng mn
hng n l qua textbox v nhn cp nhn th h thng s tin hnh chnh sa li thng
tin gi hng. Vy chng ta s x l nh th no cho trng hp .
Nu ch , cc bn s thy dng code cha textbox cho php ngi dng nhp s lng
c mt tham s c bit l name=qty[$row[id]]. Vy tham s ny c dng lm g ?.
Tham s ny, ni cho chng ta bit s lng ang hin th l thuc m sn phm no.
Vy khi tin hnh cp nht gi hng ta s kim tra, nu $qty[$row[id]] m c gi tr l 0.
Tc l ngi mun xa b gi hng. Ngc li, ta ch vic cp nht gi hng $id
tng ng vi s lng nhp textbox.
01 <?php
02 if(isset($_POST['submit']))
03 {
04 foreach($_POST['qty'] as $key=>$value)
05 {
06
if( ($value == 0) and (is_numeric($value)))
07
08
09
10
}
elseif(($value > 0) and (is_numeric($value)))
11
12
unset ($_SESSION['cart'][$key]);
$_SESSION['cart'][$key]=$value;
13
}
14 }
15 header("location:cart.php");
16 }
17 ?>
09
10
11
12
13
14
unset ($_SESSION['cart'][$key]);
$_SESSION['cart'][$key]=$value;
15 }
16 header("location:cart.php");
17 }
18 ?>
19 <html>
20 <head>
21 <title>Demo Shopping Cart - Created By My Kenny</title>
22 <link rel="stylesheet" href="style.css" />
23 </head>
24 <body>
25 <h1>Demo Shopping Cart</h1>
26 <?
27 $ok=1;
28 if(isset($_SESSION['cart']))
29 {
30 foreach($_SESSION['cart'] as $k => $v)
31 {
32
if(isset($k))
33
34
{
$ok=2;
35
}
36 }
37 }
38 if($ok == 2)
39 {
40
41
42
43
44
45
46
}
$str=implode(",",$item);
$item[]=$key;
49
50
51
52
while($row=mysql_fetch_array($query))
{
53
54
59
60
61
62
echo "</div>";
$total+=$_SESSION['cart'][$row[id]]*$row[price];
}
echo "<div class='pro' align='right'>";
69 }
70 else
71 {
72
echo "<div class='pro'>";
73
echo "<p align='center'>Ban khong co mon hang nao trong gio hang<br
/><a href='index.php'>Buy Ebook</a></p>";
74
echo "</div>";
75 }
76 ?>
77 </body>
78 </html>
V cui cng, khi ngi dng nhn xa ton b gi hng hay ch xa mt mn hng, ta s
gi ti trang delcart.php. Vy trang ny s x l nh th no ?.
Ti y, ta c th nhn tham s l: $_GET[productid'];
Tham s ny s l $id m chng truyn qua lin kt. Nu xa ton b gi hng, tc ta s
truyn cho n gi tr bng 0. Lc ny, ta s hy ton b $_SESSION[cart']. Ngc li,
nu l mt $id c th, th ta ch xa mn hng m thi. $_SESSION[cart'][$id].
Code hon chnh ca file delcart.php nh sau:
01 <?php
02 session_start();
03 $cart=$_SESSION['cart'];
04 $id=$_GET['productid'];
05 if($id == 0)
06 {
07 unset($_SESSION['cart']);
08 }
09 else
10 {
11 unset($_SESSION['cart'][$id]);
12 }
13 header("location:cart.php");
14 exit();
15 ?>
Chapter 30 : Cc hm
PHP 5 mng chc nng
Cc mng chc nng PHP l mt phn ca li PHP. Khng cn ci t s dng cc chc
nng ny.
Chc nng
M t
array ()
To ra mt mng
array_change_key_case ()
array_chunk ()
array_combine ()
array_count_values ()
array_diff ()
array_diff_assoc ()
array_diff_key ()
array_diff_uassoc ()
So snh mng v gi tr, vi mt kim tra chc nng b sung ngi dng to, v
tr li s khc bit
array_diff_ukey ()
So snh cc kha mng, vi mt kim tra chc nng b sung ngi dng to, v
tr li s khc bit
array_fill ()
in vo mt mng vi gi tr
array_fill_keys ()
array_filter ()
array_flip ()
array_intersect ()
array_intersect_assoc ()
array_intersect_key ()
array_intersect_uassoc ()
So snh mng v gi tr, vi mt kim tra chc nng b sung ngi dng to, v
tr v cc trn u
array_intersect_ukey ()
So snh cc kha mng, vi mt kim tra chc nng b sung ngi dng to, v
tr v cc trn u
array_key_exists ()
array_keys ()
Tr v tt c cc phm ca mt mng
array_map ()
array_merge ()
array_merge_recursive ()
array_multisort ()
array_pad ()
array_pop ()
array_product ()
array_push ()
array_rand ()
array_reduce ()
array_replace ()
array_replace_recursive ()
array_reverse ()
array_search ()
array_shift ()
array_slice ()
array_splice ()
array_sum ()
array_udiff ()
array_udiff_assoc ()
So snh cc kha mng, so snh gi tr mng trong mt chc nng ngi dng
to, v tr v mt mng
array_udiff_uassoc ()
array_uintersect ()
array_uintersect_assoc ()
So snh cc kha mng, so snh gi tr mng trong mt chc nng ngi dng
to, v tr v mt mng
array_uintersect_uassoc ()
array_unique ()
array_unshift ()
array_values ()
Tr v tt c cc gi tr ca mt mng
array_walk ()
array_walk_recursive ()
arsort ()
asort ()
compact ()
count ()
current ()
each ()
end ()
extract ()
in_array ()
key ()
krsort ()
ksort ()
list ()
Gn bin nh th h l mt mng
natcasesort ()
natsort ()
next ()
pos ()
prev ()
range ()
reset ()
rsort ()
Sp xp mt mng lp ch mc th t gim dn
shuffle ()
Shuffles mt mng
sizeof ()
B danh ca count ()
sort ()
uasort ()
uksort ()
usort ()
M t
PH
cal_days_in_month ()
cal_from_jd ()
cal_info ()
cal_to_jd ()
easter_date ()
easter_days ()
FrenchToJD ()
GregorianToJD ()
JDDayOfWeek ()
Tr v ngy mt tun
JDMonthName ()
Tr v mt tn thng
JDToFrench ()
JDToGregorian ()
jdtojewish ()
JDToJulian ()
jdtounix ()
JewishToJD ()
JulianToJD ()
unixtojd ()
M t
PH
CAL_GREGORIAN
Lch Gregory
CAL_JULIAN
Lch Julian
CAL_JEWISH
Do Thi lch
CAL_FRENCH
CAL_NUM_CALS
CAL_DOW_DAYNO
CAL_DOW_SHORT
CAL_DOW_LONG
CAL_MONTH_GREGORIAN_SHORT
CAL_MONTH_GREGORIAN_LONG
CAL_MONTH_JULIAN_SHORT
CAL_MONTH_JULIAN_LONG
CAL_MONTH_JEWISH
CAL_MONTH_FRENCH
CAL_EASTER_DEFAULT
CAL_EASTER_ROMAN
CAL_EASTER_ALWAYS_GREGORIAN
CAL_EASTER_ALWAYS_JULIAN
CAL_JEWISH_ADD_ALAFIM_GERESH
CAL_JEWISH_ADD_ALAFIM
CAL_JEWISH_ADD_GERESHAYIM
M t
Thay i
Ch nh v mc nh (c sn t PHP 5).Ty
chn ny c s dng bi date_sunrise () v
date_sunset ()
PHP_INI_ALL
date.default_longitude "35,2333"
Ch nh kinh mc nh (c sn t PHP
5).Ty chn ny c s dng bi date_sunrise
() v date_sunset ()
PHP_INI_ALL
date.sunrise_zenith
"90,83"
Ch nh nh cao ca mt tri mc mc nh
(c sn t PHP 5). Ty chn ny c s dng
bi date_sunrise () v date_sunset ()
PHP_INI_ALL
date.sunset_zenith
"90,83"
Ch nh mc nh hong hn nh cao (c sn
t PHP 5). Ty chn ny c s dng bi
date_sunrise () v date_sunset ()
PHP_INI_ALL
date.timezone
""
Ch nh mi gi mc nh (c sn t PHP 5.1)
PHP_INI_ALL
date.default_latitude
Mc nh
"31,7667"
M t
PH
checkdate ()
date_default_timezone_get ()
Tr v mi gi mc nh
date_default_timezone_set ()
Thit lp mi gi mc nh
date_sunrise ()
date_sunset ()
date ()
getdate ()
gettimeofday ()
gmdate ()
gmmktime ()
gmstrftime ()
Idate ()
localtime ()
microtime ()
mktime ()
strftime ()
strptime ()
strtotime ()
thi gian ()
M t
DATE_ATOM
DATE_COOKIE
DATE_ISO8601
PH
DATE_RFC822
DATE_RFC850
DATE_RFC1036
DATE_RFC1123
DATE_RFC2822
DATE_RSS
DATE_W3C
M t
PH
chdir ()
Thay i th mc hin ti
chroot ()
dir ()
M mt x l th mc v tr v mt i tng
closedir ()
ng mt x l th mc
getcwd ()
Tr v th mc hin hnh
opendir ()
M mt x l th mc
readdir ()
Tr v mt mc t mt x l th mc
rewinddir ()
t li mt x l th mc
scandir ()
PHP mc hng s
PHP : cho bit phin bn u tin ca PHP h tr cc hng s.
Lin tc
DIRECTORY_SEPARATOR
M t
PH
3
PATH_SEPARATOR
M t
PH
debug_backtrace ()
To ra mt backtrace
debug_print_backtrace ()
In mt backtrace
error_get_last ()
c cc li xy ra ln cui
error_log ()
error_reporting ()
Xc nh li c bo co
restore_error_handler ()
Phc hi x l li trc
restore_exception_handler ()
set_error_handler ()
set_exception_handler ()
trigger_error ()
user_error ()
B danh ca trigger_error ()
Lin tc
M t
E_ERROR
E_WARNING
E_PARSE
E_NOTICE
16
E_CORE_ERROR
32
E_CORE_WARNING
64
E_COMPILE_ERROR
128
E_COMPILE_WARNING
256
E_USER_ERROR
512
E_USER_WARNING
1024
E_USER_NOTICE
2048
E_STRICT
4096
E_RECOVERABLE_ERROR
6143
E_ALL
Ci t
Cc chc nng h thng tp tin l mt phn ca li PHP. Khng c ci t cn thit s dng
cc chc nng ny.
Mc nh
M t
Thay i
allow_url_fopen
"1"
PHP_INI_SYSTEM
user_agent
NULL
PHP_INI_ALL
default_socket_timeout
"60"
PHP_INI_ALL
""
PHP_INI_ALL
PHP_INI_ALL
auto_detect_line_endings "0"
M t
PHP
basename ()
chgrp ()
chmod ()
Thay i ch tp tin
chown ()
Thay i ch s hu tp tin
clearstatcache ()
copy ()
delete ()
dirname ()
disk_free_space ()
disk_total_space ()
diskfreespace ()
B danh ca disk_free_space ()
fclose ()
ng mt tp tin m
feof ()
fflush ()
Flushes m u ra vo mt tp tin m
fgetc ()
Tr v mt nhn vt t mt tp tin m
fgetcsv ()
fgets ()
Tr v mt dng t mt tp tin m
fgetss ()
file ()
c mt tp tin vo mt mng
file_exists ()
file_get_contents ()
c mt tp tin vo mt chui
file_put_contents
fileatime ()
filectime ()
filegroup ()
Tr v ID nhm ca mt tp tin
fileinode ()
Tr v s inode ca mt tp tin
filemtime ()
fileowner ()
fileperms ()
filesize ()
filetype ()
Tr v cc loi tp tin
flock ()
fnmatch ()
fopen ()
fpassthru ()
fputcsv ()
fputs ()
B danh ca fwrite ()
fread ()
c t mt tp tin m
fscanf ()
fseek ()
fstat ()
ftell ()
ftruncate ()
fwrite ()
glob ()
is_dir ()
is_executable ()
is_file ()
is_link ()
is_readable ()
is_uploaded_file ()
is_writable ()
is_writeable ()
B danh ca is_writable ()
link ()
To mt lin kt cng
linkinfo ()
lstat ()
mkdir ()
To mt th mc
move_uploaded_file ()
Di chuyn mt tp tin c ti ln mt v tr mi
parse_ini_file ()
pathinfo ()
pclose ()
ng ca mt ng ng c m bi popen ()
popen ()
M mt ng ng
readfile ()
c mt tp tin v vit n vo b m u ra
readlink ()
Tr v mc tiu ca mt lin kt mm
realpath ()
Tr v tn ng dn tuyt i
rename ()
i tn mt tp tin hoc th mc
rewind ()
rmdir ()
Loi b mt th mc rng
set_file_buffer ()
stat ()
symlink ()
tempnam ()
tmpfile ()
touch ()
umask ()
unlink ()
Xa mt tp tin
M t
PH
GLOB_NOESCAPE
PATHINFO_DIRNAME
PATHINFO_BASENAME
PATHINFO_EXTENSION
FILE_USE_INCLUDE_PATH
FILE_APPEND
FILE_IGNORE_NEW_LINES
FILE_SKIP_EMPTY_LINES
M t
PH
filter_has_var ()
filter_id ()
Tr v s ID ca mt b lc xc nh
filter_input ()
C c u vo t bn ngoi kch bn v lc n
filter_input_array ()
filter_list ()
Tr v mt mng ca tt c cc b lc c h tr
filter_var_array ()
filter_var ()
Mt bin v lc n
PHP b lc
ID Name
M t
FILTER_CALLBACK
FILTER_SANITIZE_STRING
FILTER_SANITIZE_STRIPPED
B danh ca b lc "chui"
FILTER_SANITIZE_ENCODED
FILTER_SANITIZE_SPECIAL_CHARS
FILTER_SANITIZE_EMAIL
Hy b tt c cc k t, ngoi tr ch ci, ch s v #
$% & '* + - / = ^ _ `?. {|} ~ @ []
FILTER_SANITIZE_URL
FILTER_SANITIZE_NUMBER_INT
Hy b tt c cc k t, ngoi tr ch s v + -
FILTER_SANITIZE_NUMBER_FLOAT
Hy b tt c cc k t, ngoi tr ch s, + -, v ty
chn, eE.
FILTER_SANITIZE_MAGIC_QUOTES
p dng addslashes ()
FILTER_UNSAFE_RAW
FILTER_VALIDATE_INT
FILTER_VALIDATE_BOOLEAN
FILTER_VALIDATE_FLOAT
Xc nhn gi tr nh phao
FILTER_VALIDATE_REGEXP
FILTER_VALIDATE_URL
FILTER_VALIDATE_EMAIL
Xc nhn gi tr nh e-mail
FILTER_VALIDATE_IP
Ci t
Phin bn ca s ca PHP c xy dng trong h tr cho cc phn m rng FTP. V vy,
cc chc nng FTP s lm vic t ng.
Tuy nhin, nu bn ang chy phin bn Linux ca PHP, bn s c bin dch PHP vi enable-ftp (PHP 4 +) hoc- with-ftp (PHP 3) c c cc chc nng FTP lm vic.
M t
PH
ftp_alloc ()
ftp_cdup ()
ftp_chdir ()
ftp_chmod ()
ftp_close ()
ng mt kt ni FTP
ftp_connect ()
M mt kt ni FTP
ftp_delete ()
ftp_exec ()
ftp_fget ()
ftp_fput ()
ftp_get_option ()
ftp_get ()
Ti mt tp tin t my ch FTP
ftp_login ()
ftp_mdtm ()
ftp_mkdir ()
To mt th mc mi trn my ch FTP
ftp_nb_continue ()
ftp_nb_fget ()
ftp_nb_fput ()
ftp_nb_get ()
ftp_nb_put ()
ftp_nlist ()
ftp_pasv ()
Bt ch th ng hoc tt
ftp_put ()
Ti ln mt tp tin n my ch FTP
ftp_pwd ()
Tr v tn th mc hin hnh
ftp_quit ()
B danh ca ftp_close ()
ftp_raw ()
ftp_rawlist ()
ftp_rename ()
ftp_rmdir ()
ftp_set_option ()
ftp_site ()
Gi mt lnh SITE n my ch
ftp_size ()
ftp_ssl_connect ()
ftp_systype ()
M t
PH
FTP_ASCII
FTP_TEXT
FTP_BINARY
FTP_IMAGE
FTP_TIMEOUT_SEC
FTP_AUTOSEEK
FTP_AUTORESUME
Xc nh tip tc v tr v tr v bt u nhn v t yu cu t ng
FTP_FAILED
FTP_FINISHED
FTP_MOREDATA
Ci t
Cc chc nng th mc l mt phn ca li PHP. Khng c ci t cn thit s dng cc
chc nng ny.
M t
PH
header ()
headers_list ()
headers_sent ()
setcookie ()
setrawcookie ()
Ci t
Cc chc nng ny yu cu cc gi libxml Ti v ti xmlsoft.org
M t
PH
libxml_clear_errors ()
R rng libxml li b m
libxml_get_errors ()
Ly mng li
libxml_get_last_error ()
libxml_set_streams_context ()
libxml_use_internal_errors ()
Chc nng
M t
PH
LIBXML_COMPACT
LIBXML_DTDATTR
LIBXML_DTDLOAD
Ti tp hp con bn ngoi
LIBXML_DTDVALID
Xc nhn vi cc DTD
LIBXML_NOBLANKS
Loi b cc nt trng
LIBXML_NOCDATA
t CDATA nh cc nt vn bn
LIBXML_NOEMPTYTAG
LIBXML_NOENT
Thay th cc thc th
LIBXML_NOERROR
Khng hin th cc bo co li
LIBXML_NONET
LIBXML_NOWARNING
LIBXML_NOXMLDECL
LIBXML_NSCLEAN
LIBXML_XINCLUDE
LIBXML_ERR_ERROR
Nhn c li thu hi
LIBXML_ERR_FATAL
LIBXML_ERR_NONE
Khng c li
LIBXML_ERR_WARNING
LIBXML_VERSION
LIBXML_DOTTED_VERSION
Yu cu
i vi cc chc nng mail s c sn, PHP i hi mt h thng email c ci t v
hot. Chng trnh c s dng c xc nh bi cc thit lp cu hnh trong file php.ini.
Ci t
Cc chc nng mail ny l mt phn ca li PHP. Khng c ci t cn thit s dng cc
chc nng ny.
Mc nh
M t
Thay i
SMTP
"Localhost"
PHP_INI_ALL
smtp_port
"25"
PHP_INI_ALL
sendmail_from
NULL
sendmail_path
NULL
M t
PH
ezmlm_hash ()
mail ()
Ci t
Cc chc nng ton hc l mt phn ca li PHP. Khng c ci t cn thit s dng cc
chc nng ny.
M t
PH
abs ()
Tr v gi tr tuyt i ca mt s
acos ()
Tr v arccosine ca mt s
acosh ()
asin ()
Tr v arcsine ca mt s
asinh ()
atan ()
Tr v arctangent ca mt s nh l mt gi tr s gia-PI / 2 v PI / 2
radian
atan2 ()
atanh ()
base_convert ()
Chuyn i mt s t mt c s khc
bindec ()
ceil ()
cos ()
Tr v cosin ca mt s
cosh ()
Tr v cosin hyperbol ca mt s
decbin ()
dechex ()
decoct ()
deg2rad ()
Chuyn i mt mc mt s radian
exp ()
Tr v gi tr ca E
expm1 ()
Tr v gi tr ca
floor ()
fmod ()
getrandmax ()
hexdec ()
hypot ()
is_finite ()
Tr v true nu gi tr l mt s hu hn
is_infinite ()
Tr v true nu gi tr l mt s lng v hn
is_nan ()
lcg_value ()
E-1
3
4
log ()
Tr v logarit t nhin (c s E) ca mt s
log10 ()
Tr v logarit c s-10 ca mt s
log1p ()
Tr v log (1 + s)
max ()
min ()
mt_getrandmax ()
Tr v gi tr ln nht c th c th c tr li bi mt_rand ()
mt_rand ()
mt_srand ()
octdec ()
pi ()
Tr v gi tr ca PI
pow ()
Tr v gi tr ca x sc mnh ca y
rad2deg ()
Chuyn i mt s radian n mt mc
rand ()
round ()
sin ()
Tr v sin ca mt s
sinh ()
Tr v sin hyperbol ca mt s
sqrt ()
Tr v cn bc hai ca mt s
srand ()
tan ()
Tr v tang ca mt gc
tanh ()
Tr v tang hyperbol ca mt gc
M t
PH
M_E
Tr v e (khong 2,718)
M_EULER
M_LNPI
M_LN2
M_LN10
M_LOG2E
M_LOG10E
M_PI
Tr v PI (khong 3,14159)
M_PI_2
Tr v PI / 2 (khong 1,570)
M_PI_4
Tr v PI / 4 (khong 0,785)
M_1_PI
M_2_PI
M_SQRTPI
M_2_SQRTPI
M_SQRT1_2
M_SQRT2
M_SQRT3
Ci t
Cc chc nng misc l mt phn ca li PHP. Khng c ci t cn thit s dng cc chc
nng ny.
Tn
Mc nh
M t
Thay i
ignore_user_abort
"0"
PHP_INI_ALL
highlight.string
"# DD0000"
PHP_INI_ALL
highlight.comment
"# FF8000"
Mu sc lm ni bt kin PHP
PHP_INI_ALL
highlight.keyword
"007.700"
PHP_INI_ALL
highlight.bg
"# FFFFFF"
Mu sc cho nn
PHP_INI_ALL
highlight.default
"# 0000BB"
PHP_INI_ALL
highlight.html
"# 000000"
PHP_INI_ALL
browscap
NULL
M t
PH
connection_aborted ()
connection_status ()
connection_timeout ()
constant ()
Tr v gi tr ca mt hng s
define ()
nh ngha mt hng s
defined ()
die ()
eval ()
nh gi mt chui nh l m PHP
exit ()
get_browser ()
highlight_file ()
highlight_string ()
ignore_user_abort ()
pack ()
php_check_syntax ()
php_strip_whitespace ()
show_source ()
B danh ca highlight_file ()
sleep ()
time_nanosleep ()
time_sleep_until ()
uniqid ()
To ra mt ID duy nht
unpack ()
usleep ()
M t
PH
CONNECTION_ABORTED
CONNECTION_NORMAL
CONNECTION_TIMEOUT
__COMPILER_HALT_OFFSET__
Ci t
i vi cc chc nng MySQL s c sn, bn phi bin dch PHP vi MySQL h tr.
Mc nh
M t
Thay i
mysql.allow_persistent
"1"
PHP_INI_SYSTEM
mysql.max_persistent
"-1"
mysql.max_links
"-1"
PHP_INI_SYSTEM
mysql.trace_mode
"0"
PHP_INI_ALL
mysql.default_port
NULL
PHP_INI_ALL
mysql.default_socket
NULL
4.0.1
mysql.default_host
NULL
Cc my ch lu tr my ch mc nh s
dng (khng p dng trong ch an ton
SQL)
PHP_INI_ALL
mysql.default_user
NULL
PHP_INI_ALL
mysql.default_password NULL
PHP_INI_ALL
mysql.connect_timeout
PHP_INI_ALL
"60"
Loi ti nguyn
C hai loi ti nguyn c s dng trong phn m rng MySQL. Ngi u tin l
link_identifier cho mt kt ni c s d liu, th hai l mt ngun ti nguyn m gi kt qu
ca mt truy vn.
Lu : Hu ht cc MySQL chc nng chp nhn link_identifier nh l cc tham s ty chn
cui cng. Nu n khng c cung cp, kt ni m cui cng c s dng.
M t
PH
mysql_affected_rows ()
mysql_change_user ()
mysql_client_encoding ()
Tr v tn cc b k t cho cc kt ni hin ti
mysql_close ()
mysql_connect ()
mysql_create_db ()
mysql_data_seek ()
Di chuyn con tr k lc
mysql_db_name ()
mysql_db_query ()
mysql_query () thay th
mysql_drop_db ()
mysql_errno ()
mysql_error ()
mysql_escape_string ()
mysql_fetch_array ()
mysql_fetch_assoc ()
mysql_fetch_field ()
mysql_fetch_lengths ()
mysql_fetch_object ()
mysql_fetch_row ()
mysql_field_flags ()
mysql_field_len ()
mysql_field_name ()
mysql_field_seek ()
mysql_field_table ()
mysql_field_type ()
mysql_free_result ()
B nh min ph kt qu
mysql_get_client_info ()
mysql_get_host_info ()
mysql_get_proto_info ()
mysql_get_server_info ()
mysql_info ()
mysql_insert_id ()
mysql_list_dbs ()
mysql_list_fields ()
() thay th
mysql_list_processes ()
mysql_list_tables ()
mysql_num_fields ()
mysql_num_rows ()
mysql_pconnect ()
mysql_ping ()
mysql_query ()
mysql_real_escape_string ()
mysql_result ()
mysql_select_db ()
mysql_stat ()
mysql_tablename ()
mysql_thread_id ()
mysql_unbuffered_query ()
M t
PH
MYSQL_CLIENT_COMPRESS
4,
MYSQL_CLIENT_IGNORE_SPACE
4,
MYSQL_CLIENT_INTERACTIVE
4,
MYSQL_CLIENT_SSL
4,
M t
PH
MYSQL_ASSOC
MYSQL_BOTH
MYSQL_NUM
Ct c tr v vo cc mng c ch s s (ch s bt u t 0)
Ci t
Cc chc nng SimpleXML l mt phn ca li PHP. Khng c ci t cn thit s dng cc
chc nng ny.
M t
PH
__construct ()
To mt i tng SimpleXMLElement mi
addAttribute ()
addChild ()
asXML ()
attributes ()
children ()
c cc con ca mt nt xc nh
getDocNamespaces ()
getName ()
getNamespace ()
registerXPathNamespace ()
simplexml_import_dom ()
simplexml_load_file ()
simplexml_load_string ()
xpath ()
Ci t
Cc chc nng chui l mt phn ca li PHP. Khng c ci t cn thit s dng cc chc
nng ny.
M t
PH
addcslashes ()
addslashes ()
bin2hex ()
chop ()
B danh ca rtrim ()
chr ()
chunk_split ()
convert_cyr_string ()
convert_uudecode ()
convert_uuencode ()
count_chars ()
crc32 ()
crypt ()
echo ()
Kt qu u ra chui
explode ()
fprintf ()
get_html_translation_table ()
hebrev ()
hebrevc ()
html_entity_decode ()
htmlentities ()
htmlspecialchars_decode ()
htmlspecialchars ()
implode ()
Tr v mt chui t cc yu t ca mt mng
join ()
B danh ca implode ()
Levenshtein ()
localeconv ()
LTRIM ()
md5 ()
md5_file ()
metaphone ()
money_format ()
nl_langinfo ()
nl2br ()
number_format ()
ord ()
parse_str ()
print ()
Kt qu u ra mt chui
printf ()
u ra mt chui nh dng
quoted_printable_decode ()
quotemeta ()
Du ngoc kp meta k t
rtrim ()
setlocale ()
sha1 ()
sha1_file ()
similar_text ()
Soundex ()
sprintf ()
sscanf ()
str_ireplace ()
str_pad ()
m mt chui vi di mi
str_repeat ()
str_replace ()
str_rot13 ()
str_shuffle ()
str_split ()
str_word_count ()
m s t trong mt chui
strcasecmp ()
strchr ()
strcoll ()
strcspn ()
strip_tags ()
stripcslashes ()
stripslashes ()
stripos ()
stristr ()
strlen ()
Tr v di ca mt chui
strnatcasecmp ()
strnatcmp ()
strncasecmp ()
strncmp ()
strpbrk ()
strpos ()
strrchr ()
strrev ()
o ngc mt chui
strripos ()
strrpos ()
strspn ()
strstr ()
strtok ()
strtolower ()
strtoupper ()
strtr ()
substr ()
Tr v mt phn ca mt chui
substr_compare ()
substr_count ()
substr_replace ()
trim ()
ucfirst ()
ucwords ()
vfprintf ()
vprintf ()
u ra mt chui nh dng
vsprintf ()
WordWrap ()
M t
CRYPT_SALT_LENGTH
CRYPT_STD_DES
CRYPT_EXT_DES
CRYPT_MD5
PH
CRYPT_BLOWFISH
HTML_SPECIALCHARS
HTML_ENTITIES
ENT_COMPAT
ENT_QUOTES
ENT_NOQUOTES
CHAR_MAX
LC_CTYPE
LC_NUMERIC
LC_TIME
LC_COLLATE
LC_MONETARY
LC_ALL
LC_MESSAGES
STR_PAD_LEFT
STR_PAD_RIGHT
STR_PAD_BOTH
Bi v n l da trn s kin, phn tch c php xc nhn khng, Ngi nc ngoi l nhanh
chng v thch hp cho cc ng dng web.
Cc chc nng phn tch c php XML cho php bn to ra cc phn tch c php XML v xc
nh x l cho cc s kin XML.
Ci t
Cc chc nng XML l mt phn ca li PHP. Khng c ci t cn thit s dng cc chc
nng ny.
M t
utf8_decode ()
utf8_encode ()
xml_error_string ()
xml_get_current_byte_index ()
xml_get_current_column_number ()
xml_get_current_line_number ()
xml_get_error_code ()
xml_parse ()
xml_parse_into_struct ()
xml_parser_create_ns ()
xml_parser_create ()
xml_parser_free ()
xml_parser_get_option ()
xml_parser_set_option ()
xml_set_character_data_handler ()
xml_set_default_handler ()
xml_set_element_handler ()
xml_set_end_namespace_decl_handler ()
xml_set_external_entity_ref_handler ()
xml_set_notation_decl_handler ()
xml_set_object ()
xml_set_processing_instruction_handler ()
xml_set_start_namespace_decl_handler ()
xml_set_unparsed_entity_decl_handler ()
XML_ERROR_JUNK_AFTER_DOC_ELEMENT (s nguyn)
XML_ERROR_PARAM_ENTITY_REF (s nguyn)
XML_ERROR_UNDEFINED_ENTITY (s nguyn)
XML_ERROR_RECURSIVE_ENTITY_REF (s nguyn)
XML_ERROR_ASYNC_ENTITY (s nguyn)
XML_ERROR_BAD_CHAR_REF (s nguyn)
XML_ERROR_BINARY_ENTITY_REF (s nguyn)
XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF (s nguyn)
XML_ERROR_MISPLACED_XML_PI (s nguyn)
XML_ERROR_UNKNOWN_ENCODING (s nguyn)
XML_ERROR_INCORRECT_ENCODING (s nguyn)
XML_ERROR_UNCLOSED_CDATA_SECTION (s nguyn)
XML_ERROR_EXTERNAL_ENTITY_HANDLING (s nguyn)
XML_OPTION_CASE_FOLDING (s nguyn)
XML_OPTION_TARGET_ENCODING (s nguyn)
XML_OPTION_SKIP_TAGSTART (s nguyn)
XML_OPTION_SKIP_WHITE (s nguyn)
Ci t
i vi cc chc nng tp tin Zip lm vic trn my ch ca bn phi c ci t, cc th
vin:
PHP 5 +: chc nng Zip v th vin Zip khng c kch hot theo mc nh v phi c ti
v t cc lin kt trn. S dng - vi-zip = DIR cu hnh ty chn bao gm h tr Zip.
Cc h thng ci t trn
PHP 5 +: chc nng Zip khng c kch hot theo mc nh, v vy php_zip.dll v th vin
ZZIPlib phi c ti v t lin kt trn. php_zip.dll phi c kch hot bn trong php.ini.
kch hot bt k phn m rng PHP, PHP extension_dir thit lp (trong file php.ini) nn
c t vo th mc ni m cc phn m rng PHP c t. Mt gi tr extension_dir v d
l c: \ php \ ext.
M t
PH
zip_close ()
ng mt file ZIP
zip_entry_close ()
zip_entry_compressedsize ()
zip_entry_compressionmethod ()
zip_entry_filesize ()
zip_entry_name ()
zip_entry_open ()
zip_entry_read ()
zip_open ()
M mt tp tin ZIP
zip_read ()
_Interface
VD: Zend_Db_Table_Interface
Tn file :
Ch nhng k t, s , du gch di ( _ ) v du gch ngang ( - ) c chp nhn.
Cc file cha php code phi c extension l .php ( tr nhng file View c mc nh l
.phtml )
Tn file phi tun th vic tr n cc tn class nh trn :
VD:
Zend/Db.php
Zend/Controller/Front.php
Hm v phng php :
Tn hm ch nn dng k t, gch di ( _ ) khng c chp nhn . Trong tn hm c
th c cc con s nhng khng c khuyn khch
Tn hm phi lun lun bt u bi cc k t thng . Khi tn hm gm nhiu t, k t
u tin ca t th 2 tr i phi c vit hoa
Tn hm c th rm r, nhng n phi c ngha v d on c chc nng ca n
VD:
PHP Code:
filterInput()
getElementById()
widgetFactory()
Cc tham s mc nh trong hm
S dng NULL thay cho FALSE nu t mc nh
VD:
PHP Code:
Public function foo($required, $optional
= NULL)
Coding Style
Tags :
PHP code phi c bao trong <?php ?> . Khng c dng dng tt : <? ?>
Chui :
Chui literal:
Khi chui hok c bin trong ( gi l literal) , th phi c khai bo vi nhy n ' ' .
Chui Literals c bao gm nhy n bn trong :
Khi chui c bao gm nhy n trong, chng ta phi khai bo n bng nhy i " " .
Ni suy bin :
2 dng sau c chp nhn trong vic ni suy bin :
PHP Code:
$greeting = "Hello $name, welcome back!";
$greeting = "Hello {$name}, welcome back!";
Hok hp l:
PHP Code:
$string = "$string1"."$string2"
Mng :
Mng tun t :
S m khng c chp nhn trong vic nh s th t phn t trong mng .
Vic nh s th t ca tt c cc mng phi c bt u bi s 0 .
Khi khi to mng, 1 khong trng cn phi c thm vo sau mi du ,.
VD:
PHP Code:
Hok hp l:
PHP Code:
$sampleArray = array('first','second','third');
Mng c th c khi to trn nhiu dng . V phi thm khong trng vo dng th 2
tr i ngang hng vi dng 1
VD:
PHP Code:
$sampleArray = array('first', 'second', 'third'
'fourth', 'fifth' , 'sixth'
'seventh', 'eighth', 'ninth')
Lp
Khai bo lp
K t m class ( { ) phi c t ngay sau dng khai bo tn class.
Mi dng code bn trong class phi c thc dng 4 khong trng .
Ch 1 class trong 1 file PHP
Thm code vo trong 1 file cha class c th c nhng hok c khuyn khch
PHP Code:
/**
* class Docblock Here
*/
class Zend_Class
{
// entire content of class
// must be indented four spaces
}
Hm v methods :
Cc method phi c khai bo vi cc t : privated, protected, public. Khng c b
trng
Static method phi c khai bo vi theo u tin ca visibility trong script
VD:
PHP Code:
public
static foo() { ... }
private
static bar() { ... }
protected static goo() { ... }
Hok hp l:
PHP Code:
public function functionName()
{
return ($this->varName);
}
Nu mun truyn tham tr, th phi t & trc bin trong hn khai bo hm , khng
c khi s dng hm mi thm du & .
Khi tham s ca hm c th l mng, khi gi hm c th dng array construct v c th
phn ct mng ra nhiu dng
VD:
PHP Code:
threeArguments(array(1, 2, 3), 2, 3);
threeArguments(array(1, 2, 3, 'Zend', 'Studio',
$a, $b, $c,
56.44, $d, 500), 2, 3);
Cu lnh iu khin
If/ Else/ Elseif
Cc cu iu kin phi c 1 khong trng gia t if, elseif v ngoc m ( . Thm
1 khong trng na gia ngoc ng ) v ngoc cong {.
trong ngoc n (), gia 2 bn ca cc ton t so snh phi c khong trng d
c .
Ngoc cong m { phi vit chung hng vi lnh if . Ngoc cong ng phi hng ca
ring n
VD:
PHP Code:
if ($a != 2){
$a = 2;
}
Hok hp l:
PHP Code:
if($a!=2)
{
$a=2;}
} else {
$a = 7;
}
Tt c cc lnh if, elseif hay else phi c {} . Mc d trong vi trng hp hok c chy
dc .
Phi dng elseif , rt khng khuyn khch dng else if
Switch
Tng t, gia ch switch v ngoc m ( phi c 1 khong trng, v gia ngoc
ng ) v { phi c 1 khong trng na .
Ngoc cong m { phi nm chung hng vi if , v ngoc cong ng } phi nm
hng ca ring n
Tt c cc ni dung bn trog switch phi c thc dng 4 khong trng . V ni dung
ca mi case phi c thc dng thm 4 khong trng na !
PHP Code:
switch ($numPeople) {
case 1:
break;
case 2:
break;
default:
break;
}
Inline Documentation
K t # hok nn dng comment trong code .
Files:
Trong mi file cha PHP code, chng ta phi c 1 block trn u file miu t v file
.
Bn c th lm nh sau :
PHP Code:
/**
* Short description for file
*
* Long description for file (if any)...
*
* LICENSE: Some license information
*
* @copyright 2006 Zend Technologies
* @license
[url]http://www.zend.com/license/3_0.txt[/url]
ense 3.0
PHP Lic
* @version
* @link
* @since
*/
$Id$
[url]http://dev.zend.com/package/PackageName[/url]
File available since Release 1.2.0
Classes
Tng t nh vy, cc class cng cn phi c
PHP Code:
/**
* Short description for class
*
* Long description for class (if any)...
*
* @copyright 2006 Zend Technologies
* @license
[url]http://www.zend.com/license/3_0.txt[/url]
PHP Lic
ense 3.0
* @version
Release: @package_version@
* @link
[url]http://dev.zend.com/package/PackageName[/url]
* @since
Class available since Release 1.2.0
*/
Functions
Vi mi hm, bao gm c cc hm dc nh ngha trong class, cn c 1 block gm:
Miu t c bn v hm
Tt c cc bin ca hm
Tt ca cc gi tr tr v ca hm
Nu 1 hm hay 1 method trong class c throw exception th dng @throw
VD:
PHP Code:
/**
* Does something interesting
*
* @param Place
$where Where something interesting takes place
* @param integer $repeat How many times something interesting should
happen
* @throws Some_Exception_Class If something interesting cannot happen
* @return Status
*/
public function doSomethingInteresting(Place $where, $repeat = 1)
{
// implementation...
}
Require v include
Include, include_once, require, require_once hok nn dng () .
VD :
PHP Code:
include 'header.php';
Hok hp l:
PHP Code:
include ('header.php');
return 'Tuts';
}
}
class NetTuts
{
use Net, Tuts;
public function plus()
{
return '+';
}
}
$o = new NetTuts;
echo $o->net(), $o->tuts(), $o->plus();
echo (new NetTuts)->net(), (new NetTuts)->tuts(), (new NetTuts)>plus();
<?php
// index.php
echo 'Hello Nettuts+ Readers!';
?>
Save file li v n bc 2
Bc 2 : chy web server .
M command promt ( Window + R, g cmd, nhn enter ) . Bn s thy 1 ci g i
loi nh :
M:
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\Documents and Settings\nettuts>
v paste vo command promt ( click chut phi , chn paste ). Nhn enter . Nu tt c
chy ng, bn s thy 1 ci g i loi nh bn di ^^ : ( lu hok c ng
command promt, nu ng, web server s b tt )
M:
C:\php>php -S 0.0.0.0:8080 -t C:\public_html router.php
PHP 5.4.0 Development Server started at Fri Mar 02 09:36:40 2012
Listening on 0.0.0.0:8080
Document root is C:\public_html
Press Ctrl-C to quit.
M browser ln v type vo :
M:
http://localhost:8080/index.php
bn s thy :
Hello Nettuts+ Readers!
Lu 1 : to 1 file php-server.bat vi ni dung sau
M:
C:\php\php -S 0.0.0.0:8080 -t C:\public_html router.php.
cp t internet !
C php mng ngn gn
PHP 5.4 cung cp 1 c php mng ngn gn :
PHP Code:
$fruits = array('apples', 'oranges', 'bananas'); // "old" way
// Khai bo mng nh kiu Javascript
$fruits = ['apples', 'oranges', 'bananas'];
// Mng hok tun t
$array = [
'foo' => 'bar',
'bar' => 'foo'
];
Cu lnh trn s chy tt, nhng s hin ra 1 li E_STRICT (chun Strict : ch bin mi
c truyn tham tr ) . Bi v n tr thnh 1 phn ca E_ALL trong error-reporting.
Mt v d nng cao :
PHP Code:
function foobar()
{
return ['foo' => ['bar' => 'Hello']];
}
echo foobar()['foo']['bar']; // Hello
PHP Code:
class Foo
{
function hello() {
echo 'Hello Nettuts!';
}
function anonymous()
{
return function() {
$this>hello(); // $this kiu ny s hok chy c trong cc phin bn trc
.
};
}
}
class Bar
{
function __construct(Foo $o) // i tng ca class Foo typehint
{
$x = $o->anonymous(); // ly ra Foo::hello()
$x(); // chy Foo::hello()
}
}
new Bar(new Foo); // Xut Hello Nettuts!
Tag <?=
Mc k setting trong php.ini, short_open_tag , <?= (open PHP tag v echo ) s lun lun
available . C ngha l bn c th an ton dng :
PHP Code:
<?=$title?>
Thay v
PHP Code:
<?php echo $title ?>
V d: din t s 31 chng ta c
PHP Code:
echo
echo
echo
echo
Callable Typehint
Typehint c s dng tng cng sc mnh ca PHP . Typehint c th l array, l
object t PHP 5.1 v l callable t PHP 5.4 . Cc kiu typehint truyn thng : int hay
string s hok c h tr na !!
PHP Code:
function my_function(callable $x)
{
return $x();
}
function my_callback_function(){return 'Hello Nettuts!';}
class Hello{static function hi(){return 'Hello Nettuts!';}}
class Hi{function hello(){return 'Hello Nettuts!';}}
echo my_function(function(){return 'Hello Nettuts!';}); // anonymous fu
nction
echo my_function('my_callback_function'); // callback function
echo my_function(['Hello', 'hi']); // class name, static method
echo my_function([(new Hi), 'hello']); // class object, method name
Li kt
V mt tng th, PHP 5.4 cung cp 1 s lng ln ci tin .
Bn ngh PHP 5.5 s mang ti cho chng ta ci tin no v bn mong i iu g ?
NGUN: Dch t http://net.tutsplus.com/tutorials/ph...you-must-know/ !
Cc hm rt hu ch trong PHP bn
cn bit !
1/ Hm c bao nhiu tham s cng c
Page 235 of 413
File cng c th c ly ra vi ng dn :
PHP Code:
$files = glob('../images/a*.jpg');
print_r($files);
/* Xut
Array
(
[0] => ../images/apple.jpg
[1] => ../images/art.jpg
)
*/
PHP Code:
$files = glob('../images/a*.jpg');
// s dng hm n mi phn t mng
$files = array_map('realpath',$files);
print_r($files);
/* output looks like:
Array
(
[0] => C:\wamp\www\images\apple.jpg
[1] => C:\wamp\www\images\art.jpg
)
*/
4/Magic Constants
PHP cung cp mt s magic_constants hu ch nh :
Bn hy chy script trn, ng to file database.php trong folder config nh, hiu
__FILE__ c nhim v g, bn c vic copy->paste-> chy . Bn s thy li cha ?
Nu thy ri, bn o th t ca 2 dng require_once() trn, bn chy li v s hiu ^^
Lu : nn s dng __FILE__ khi include script khc bn nh .
S dng __LINE__ s gip chng ta debug d hn . Bn c th tm ra s th t ca dng
:
PHP Code:
// some code
// ...
my_debug("some debug message", __LINE__);
/* Xut
Line 4: some debug message
*/
// some more code
// ...
my_debug("another debug message", __LINE__);
/* Xut
Line 11: another debug message
*/
function my_debug($msg, $line) {
echo "Line $line: $msg\n";
}
5/ To ID c bit :
C 1 vi trng hp chng ta cn phi to ra nhng chui c bit ( khng trng lp ),
ngi ta thng dng md5() lm iu ny, nhng md5() khng thc s sinh ra lm
iu !
PHP Code:
// generate unique string
echo md5(time() . mt_rand(1,1000000));
/* Xut
4bd67c947233e
*/
// To 1 chui c bit khc
echo uniqid();
/* Xut
4bd67c9472340
*/
echo $string;
/* Xut
a:4:{i:0;s:5:"hello";i:1;i:42;i:2;a:2:{i:0;i:1;i:1;s:3:"two";}i:3;s:5:"
apple";}
*/
// Bn c th ly li mng ban u
$newvar = unserialize($string);
print_r($newvar);
/* Xut
Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)
[3] => apple
)
*/
[0] => 1
[1] => two
)
[3] => apple
)
*/
8/ ng k 1 hm shutdown
Vi hm register_shutdown_function(), chng ta c th lm 1 vi chuyn trc khi
script ngng chy .
V d m thi gian chy script n :
PHP Code:
// Ly thi gian bt u chy
$start_time = microtime(true);
// Code y
// ...
// Xut code chy c bao lu ri
echo "Thi gian chy script : ".
(microtime(true) - $start_time).
" seconds.";
iu g khin bn l 1 coder ti ?
Page 243 of 413
Tt c chng ta u c nhng thi quen xu, chng ta s tm hiu , cng nhau kim tra,
nh gi li v sa ngay lp tc !
Bn hok c k hoch trc khi bt u code
Trc khi bn bt u code, bn cn phi c 1 chin lc . iu ny s gip bn theo di
c code, v trnh vic khng hiu code s khin bn nhc u, y l cha mn n
nhng linh hn ti nghip khc c code ca bn =]]]
Mt cch khc phc iu ny l vit mt on phc tho cc chc nng ca on
script bng cch comment u file
V d :
PHP Code:
<?php
// Include necessary data
// Initialize the database connection
// Include the common header markup
// Determine the page variables from the POST data
// Load the proper database info using the page vairiables
// Loop through the loaded rows
// Format the images for display
// Create a permalink
// Format the entry for display
// Add the formatted entry to the entry array
// Collapse the entry array into page-ready markup
// Output the entries
// Include the common footer markup
Bn khng comment g c
Vn ti t nht l khi chng ta code, chng ta khng comment y , hoc thm ch
khng comment .
Khi chng ta cn phi chnh sa code, c th s gy hng c ng dng .
Qu trnh comment code s din ra trong khong t 10 pht ti 6 gi !
V d :
PHP Code:
$pieces = explode('.', $image_name);
$extension = array_pop($pieces);
Bn lp li code
Khi bn quan st code ca bn, nu bn gp li , hy t hi , mnh c cn phi sa nhiu
hn 1 file ? Nu bn tr li c, n lc nhn li cch bn code !!!
Nu bn c nhiu on code cng chc nng , bn ang lm sai y !
Bn khng theo 1 m hnh no c
Code ca bn cn phi c 1 m hnh .Ti khng ng bn nn dng m hnh MVC hay
Page 246 of 413
i loi vy. ti l bn cn phi bit cch phn loi cc thnh phn, ni dung , v.v v
nhng thnh phn, ni dung y s lm g
Khi bn code theo 1 m hnh, nhiu quyt nh s tr nn t ng ha, v khi 1 ngi
no xem code bn, h s hok phi on nhiu khi tm kim 1 chc nng no .
Lm iu ny s hok mt nhiu thi gian, nhng s gip bn rt nhiu y !
Vy bn hy c gng code theo 1 m hnh nh !!!!
Bn cnh , bn hok nn code theo kiu t cho mnh l 1 chuyn gia !! Vi 1 trit l i
loi l : nu bn hok hiu code mnh, tt nht ng nn c n .
y l 1 cch tip cn anti cng ng, v hok c tnh xy dng, hng dn . V 1 lp
trnh vin nh vy s hok c s gip ca mi ng khi anh ta gp vn vi code .
V vy, trnh vic to code kh hiu di mi hnh thc nh . iu s hok khin bn thng minh hn
hay nhn c nhiu s tn trng hn u .
bn tm c trong nhng ngi ny 1 ngi c cch tip cn v phong cch vit code
ging bn , bn c th hc hi h .
Vic theo di bi vit ca vi ngi hp vi bn s tt hn nhiu so vi theo di mi
blog cng ngh bn gh qua vi 1 vi l do sau :
Bn khng dm i mt vi th thch
Nu bn khng dm i mt vi th thch, th bn c vn ri y .
Hy tm 1 vi th thch trong d n bn ang lm !
T hi bn cc cu sau khi ang xem d n :
Bn hok chia s
Hy ci thin bng cch trao i, tho lun vi cc ng nghip coders nh . lm c
iu ny c nhiu cch : Nu bn hiu r 1 vn no , hy vit tutorial v n v cung
cp m ngun . Nu bn hok thch nh th, bn c th lt qua vi din n v gip
nhng ngi mi .
Bn s hi : Ti sao gip nhng ngi mi s gip ti tin b ?
V vy.hy dng li
Chng ta u khng hon ho . Nhng chng ta c th lm mi th vi nng lc ca
mnh cng gn ch chng ta mun cng tt ................
Trch dn: hc hi t 1 ti liu ting anh, v vit li theo phong cch ca mnh thm vo
1 vi v d
Xong !
Chc thnh cng
Kt ni database
PHP Code:
<?php
//=============================Kt ni csdl ===========================
==========
$host="localhost";
$u="root";
$p="root";
$db="demo_db";
$result=NULL;
$conn=NULL;
$conn=@mysql_connect($host,$u,$p) or die ("Ket noi server that bai"
);
if($conn)
{
@mysql_select_db($db,$conn) or die("Ket noi database that bai")
;
}
mysql_query('SET CHARACTER SET utf8');
//=====================================================================
==========
?>
while($rows2=mysql_fetch_array($result2))
{
?>
<div><a href="index.php?cate=<?php echo $rows2['id']; ?>">
- <?php echo $rows2['name']; ?></a></div>
<?php
}
?>
</div>
<!-- Ht Sub menu -->
<?php
}
?>
Cui cng l cho n bung sub menu ra theo iu kin. dng javascript
HTML Code:
<!-- X sub menu -->
<script>
var id='<?php echo $_GET['cate']; ?>';
var sub_menu='sub_'+id;
if(document.getElementById(sub_menu))
document.getElementById(sub_menu).style.display='block';
else
{
<?php
$cate=$_GET['cate'];
$sql="select * from cate_news where id='".$cate."'";
$result=mysql_query($sql);
if(mysql_num_rows($result)>0)
{
$rows=mysql_fetch_array($result);
?>
var id='<?php echo $rows['parent']; ?>';
var sub_menu='sub_'+id;
if(document.getElementById(sub_menu))
document.getElementById(sub_menu).style.display='block';
<?php
}
?>
}
</script>
T lm im sng vi javascript
ci ny trn mng c code sn v vit bng jquery, nhng m mnh t vit li v mnh vit
mnh s hiu r v chnh sa d dng hn rt nhiu, v hiu r c mt s ci mi na.
Tht s n ch l ci div ni ln trn m thi
c cc c im sau:
- Khi vo trang index hin ra 1 pop-up qung co nh, nm gia trang web.
- T tt sau 5s.
- C nt Close tt.
- Lm m background trang web.
DEMO
u tin l nh dng
HTML Code:
<style>
#popup
{
position:fixed;
z-index:99999;
background:#FFFFFF;
border:5px solid #003300;
padding:5px 0px 5px 5px;
display:none;
}
#bg_trans
{
position:fixed;
z-index:99998;
display:none;
background-color:#000000;
opacity:0.4;filter: alpha(opacity=40);
-msfilter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=40)";
}
</style>
t thuc tnh onload hoc l gi lm t cui trang web cng khng sao
HTML Code:
<body topmargin="0" leftmargin="0" onload="show_popup();">
- ci popup v nn
HTML Code:
<div id="popup" style="width:200px;">
<!-- //////////////////////////////////////////////////
-->
<!-- Nt close -->
<!-- //////////////////////////////////////////////////
-->
<div style="width:27px; right:0px; top:0px; height:18px;
position:absolute; z-index:999999; background:url(x.jpg);
cursor:pointer;" onclick="hide_popup();"></div>
<!-- ht nt close ////////////////////////////////////
-->
<!-- Ni dung y -->
<!-- //////////////////////////////////////////////////
-->
ni dung popup ni dung pop-up <br />
ni dung popup ni dung pop-up<br />
ni dung popup ni dung pop-up<br />
ni dung popup ni dung pop-up<br />
ni dung popup ni dung pop-up<br />
ni dung popup ni dung pop-up<br />
ni dung popup ni dung pop-up<br />
ni dung popup ni dung pop-up<br />
ni dung popup ni dung pop-up<br />
<!-- ht ni dung /////////////////////////////////////
-->
</div>
<div id="bg_trans">
</div>
HTML Code:
<script>
var time=5; // thi gian
time=(time*10)-10;
var count=0;
var type;
type=navigator.appName;
function show_popup()
{
count++;
if(type=="Microsoft Internet Explorer")
{
if(document.compatMode=="BackCompat")
{
var height=document.body.offsetHeight;
}
else
{
var
height=document.documentElement.offsetHeight;
}
}
else
{
var height=window.innerHeight;
}
if(document.compatMode=="BackCompat")
var width=document.body.offsetWidth;
else
var width=document.documentElement.offsetWidth;
document.getElementById('popup').style.display='block';
document.getElementById('bg_trans').style.display='block';
document.getElementById('bg_trans').style.width=width+'px';
document.getElementById('bg_trans').style.height=height+'px';
var
t_width=document.getElementById('popup').offsetWidth;
var
t_height=document.getElementById('popup').offsetHeight;
document.getElementById('bg_trans').style.top="0px";
document.getElementById('bg_trans').style.left="0px";
var mar_top=(height/2)-(t_height/2);
var mar_left=(width/2)-(t_width/2);
document.getElementById('popup').style.top=mar_top+"px";
document.getElementById('popup').style.left=mar_left+"px";
if(count<=time)
{
setTimeout("show_popup()",100);
}
else
{
document.getElementById('popup').style.display='none';
document.getElementById('bg_trans').style.display='none';
}
}
function hide_popup()
{
time=0;
document.getElementById('popup').style.display='none';
document.getElementById('bg_trans').style.display='none';
}
</script>
- Chy http://localhost/myWebsite/index.php v
xem kt qu
Smarty c bn [ Phn 1 ]
BI 1: HIN TH D LIU T MYSQL BNG SMARTY
1.Hinh nh bi tp
:2.Hng dn ci t smarty:
<tr>
<td width="38%" bgcolor="#CCCCCC">
<strong>Ti khon ca {$students[st].nick}</strong>
// Ly d liu ca trng nick tng ng trong MYSQL
</td>
<td width="62%"> </td>
</tr>
<tr>
<td><font><b>Tn: </b></font></td>
<td><font><b><bgcolor="#CCCCCC">{$students[st].name}</b></font></td>
</tr>
<tr>
<td>Ngy sinh</td>
<td>{$students[st].ngaysinh}</td
<tr>
<tr>
<td>Nhm</td>
<td>{$students[st].nhom}</td
<tr>
<tr>
<td>Email</td>
<td>{$students[st].email}</td
<tr>
</table>
<br />
{/section}
</body>
</html>
Smarty c bn [ Phn 2 ]
Xin cho cc bn phn I cc bn c nm c cch ci t smarty v
khi chy chng trnh vi bi tp show d liu ra bn ngoi
trong phn II bi tp s kh hn mt cht, cc bn s phi to lin kt gia 3
bng v show n ra ngoi mn hnh, ngoi ra phn ny mnh s thm to
style c bn cho cc bn.
Bi tp:
Cc bn to mt file c tn daily_banhang.php
on m nh sau:
PHP Code:
<?php
include("../libs/smarty.class.php");
$smarty = new smarty();
mysql_connect("localhost","root","mysql") or die ("Li khng th kt n
i ti CSDL");//Dng ny l kt ni CSDL ca cc bn
mysql_select_db("daily_banhang") or die ("Li khng th kt ni ti Dat
abase");
// Dng ny l kt ni ti Database
$sql=mysql_query("SELECT
ten_khuvuc,
ten_daily,
ten_mathang,
dongia,
soluong,
(dongia*soluong) as tong_tien
FROM khuvuc
INNER JOIN ketqua on khuvuc.id_khuvuc=ketqua.id_khuvuc
</html>
<style>
#cottieude{
text-transform: uppercase;
background-color:#25510D;
color: #EEEEEC;
}
#cotbang{
background-color:#ACABAB;
text-weight:bold;
text-align:center;
</style>
$abc->demo();
?>
function __autoload($url){
$url=str_replace("_","/",$url);
require("$url.php");
}
Regular Expressions
1. Regular expression l g?
+ Biu thc chnh quy.
+ Hiu nm na l 1 chui c quy tc m t nhng chui(string) khc
2. C php c bn ( y mnh ch trnh by v v d cho ngn ng php)
Example:
PHP Code:
<?php
$re = '/hello/'; // biu thc chnh quy cho mt string c chui hello
trong .
$str = 'hello world';
if(preg_match($re, $str)) {
echo 'Yes';
}
?>
Output: Yes
+ K hiu ^ v $: bt u v kt thc 1 string
Example:
PHP Code:
<?php
$re = '/^hello/'; // biu thc chnh quy cho mt string bt u bi ch
ui hello
$str = 'hello world';
if(preg_match($re, $str)) {
echo 'Yes';
}
else {
echo 'No';
}
?>
Output: Yes
PHP Code:
<?php
$re = '/hello$/'; // biu thc chnh quy cho mt string kt thc bi ch
ui hello
$str = 'hello world';
if(preg_match($re, $str)) {
echo 'Yes';
}
else {
echo 'No';
}
?>
Output: No
+ K hiu: *, +, ?
$re = '/^ab*$/' ; // biu thc chnh quy cho mt string bt u bi a, v kt thc l 0 hoc
nhiu b (v d: a, ab, abb, abbb, );
$re = '/^ab+$/' ; // biu thc chnh quy cho mt string bt u bi a, v kt thc l 1 hoc
nhiu b (v d: ab, abb, abbb, );
$re = '/^ab?$/' : // biu thc chnh quy cho mt string bt u bi a, v kt thc l b hoc
l khng (v d: ab hoc a).
Example:
PHP Code:
<?php
$re = '/^ab*$/';
$str = 'abbc';
if(preg_match($re, $str)) {
echo 'Yes';
}
else {
echo 'No';
}
?>
Output: No
+ S dng: {}:
$re = '/^ab{2}$/'; // biu thc chnh quy cho mt string bt u bi a, v kt thc l 2 ch
b (l abb);
$re = '/^ab{2,}$/'; // biu thc chnh quy cho mt string bt u bi a, v kt thc l t
nht 2 ch b (v d: abb, abbb, abbbb, );
$re = '/^ab{2,5}$/'; // biu thc chnh quy cho mt string bt u bi a, v kt thc l t
nht 2 ch b v nhiu nht l 5 ch b (v d: abb, abbb, abbbb, abbbbb);
+ S dng : () v |
$re = '/^a(bc)*$/'; // biu thc chnh quy cho mt string bt u bi a, v kt thc l 0
hoc nhiu 'bc' (v d abc, abcbc, abcbcbcbc, )
$re = '/^a(b|c)*$/'; // biu thc chnh quy cho mt string bt u bi a, v kt thc l 0
hoc nhiu 'b' hoc nhiu 'c' hoc 'b' 'c' ln ln :D (v d abc, abbcccccccccc,
abccccbbbcbc, )
+ S dng symbol '.': i din cho mt k t n bt k
$re = '/^.{3}$/'; //Biu thc chnh quy cho mt chui c ng 3 k t bt k.
PHP Code:
<?php
$re = '/^.{3}$/';
//Biu thc chnh quy cho mt chui c ng 3 k t bt k.
$str = '&#%';
if(preg_match($re, $str)) {
echo 'Yes';
}
else {
echo 'No';
}
?>
Output: Yes
+ S dng: '-':
[0-9] : Mt ch s
[a-zA-Z]: mt k t A->Z, a->z
[a-d] : ~ (a|b|c|d)
[^a-zA-Z]: mt k t khng phi l A->Z, a->z
[^0-9]: mt k t khng phi l s
+ S dng: '\'
\d - Ch s bt k ~ [0-9]
\D - K t bt k khng phi l ch s (ngc vi \d) ~ [^0-9]
\w - K t t a-z, A-Z, hoc 0-9 ~ [a-zA-Z0-9]
\W - Ngc li vi \w (ngha l cc k t khng thuc cc khong: a-z, A-Z, hoc 0-9)
~[^a-zA-Z0-9]
\s - Khong trng (space)
\S - K t bt k khng phi l khong trng.
3. Cc hm c bn vn dng regular expression
+ preg_match : http://php.net/manual/en/function.preg-match.php
int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int
$offset = 0 ]]] )
C bn l tm kim 1 string c lm vic theo mt $re.
V d:
PHP Code:
<?php
$re = '/^\w+$/';
// mt string ton k t A->Z, a->z, 0->9
$str = 'quya*';
if(preg_match($re, $str)) {
echo 'Yes';
}
else {
echo 'No';
}
?>
Output: No
+ preg_replace: http://www.php.net/manual/en/function.preg-replace.php
mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit
= -1 [, int &$count ]] )
C bn l tm kim trong 1 string nhng chui c cu trc theo $re thay th
V d:
PHP Code:
<?php
$re = '/\w+$/';
$str = '*quya';
echo preg_replace($re, 'hi', $str);
?>
Output: *hi
+ preg_split: http://php.net/manual/en/function.preg-split.php
Page 271 of 413
array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )
V d:
Cc bn xem tm v d trong php manual nh. Mt ri.
Khi s dng modifier x th khong trng trong biu thc chnh quy s c b qua, nu
khng n s c escaped (\s). iu ny d dng thm comment. Comment s bt u
bng du # v kt thc ti 1 dng mi.
II. Greedy v Ungreedy:
hiu c phn ny bn cn xem qua v d sau:
V d: Mnh c 1 on m html sau khi view source ca 1 trang web
M:
<html>
<head><title>Greedy v Ungeedy</title></head>
<body>
<p id=weather>
Ni dung cn ly nm y
</p>
<p>
Ni dung khc
</p>
</body>
</html>
Vy ly ni dung trong th <p id=weather></p>, mnh s phi vit biu thc sau:
PHP Code:
$parttern = /<p id=\weather\>(.*)</p>/s;
if(preg_match($parttern, $html, $match))
{
print_r($match);
}
H h, kt qu th no cc bn s ly c ni dung cn ly ch.
M:
Array (
[0] =>
Ni dung cn ly y
Ni
[1]
Ni
Ni
)
dung khc
=>
dung cn ly y
dung khc
Chy li code
PHP Code:
$parttern = /<p id=\weather\>(.*?)</p>/s;
if(preg_match($parttern, $html, $match))
{
print_r($match);
}
bn s nhn c kt qu nh
M:
Page 273 of 413
Array (
[0] =>
Ni dung cn ly y
[1] =>
Ni dung cn ly y
)
'1', 'name'
=> '0'),
'2', 'name'
=> '1'),
'3', 'name'
=> '2'),
'4', 'name'
tng nh sau. sau khi c ci mng ri th mnh dng m php select theo iu
kin thay cho sql. bin $current_menus chnh l menu cn hin th hin ti
V cui cng l show menu ra thi
PHP Code:
show_menu($menus);
Code full:
PHP Code:
$menus = array(
array('id' => '1', 'name' => 'LEVEL 1', 'link' => 'localhost/trangc
hu.php', 'parent' => '0'),
array('id' => '2', 'name' => 'LEVEL 2', 'link' => 'localhost/trangc
hu.php', 'parent' => '1'),
array('id' => '3', 'name' => 'LEVEL 3', 'link' => 'localhost/trangc
hu.php', 'parent' => '2'),
array('id' => '4', 'name' => 'LEVEL 4', 'link' => 'localhost/trangc
hu.php', 'parent' => '3'),
array('id' => '5', 'name' => 'LEVEL 1', 'link' => 'localhost/trangc
hu.php', 'parent' => '0'),
array('id' => '6', 'name' => 'LEVEL 1', 'link' => 'localhost/trangc
hu.php', 'parent' => '0'),
array('id' => '7', 'name' => 'LEVEL 2', 'link' => 'localhost/trangc
hu.php', 'parent' => '6'),
array('id' => '8', 'name' => 'LEVEL 2', 'link' => 'localhost/trangc
hu.php', 'parent' => '6'),
array('id' => '9', 'name' => 'LEVEL 2', 'link' => 'localhost/trangc
hu.php', 'parent' => '6'),
array('id' => '10', 'name' => 'LEVEL 3', 'link' => 'localhost/trang
chu.php', 'parent' => '9'),
array('id' => '11', 'name' => 'LEVEL 3', 'link' => 'localhost/trang
chu.php', 'parent' => '9'),
array('id' => '12', 'name' => 'LEVEL 3', 'link' => 'localhost/trang
chu.php', 'parent' => '9')
);
function show_menu($menus = array(), $parrent = 0)
{
// LAY MENU DUA VAO ID MENU CHA
$current_menus = array();
foreach ($menus as $key => $val) {
if ($val['parent'] == $parrent) {
$current_menus[] = $val;
unset($menus[$key]);
}
}
// SHOW RA MENU THEO UL
if (sizeof($current_menus) > 0) {
echo '<ul>';
foreach ($current_menus as $key => $val) {
echo '<li><a href="', $val['link'], '">', $val['name'], '</
a>';
show_menu($menus, $val['id'], false);
echo '</li>';
}
echo '</ul>';
}
}
show_menu($menus);
2/ VD upload file
+ form upload
+ X l upload
$found = $search;
}
return $found;
}
public static function lang($key) {
$group = explode('.', $key);
$key_lang = $group[1];
$group = $group[0];
$mes = array();
if (!isset(self::$language_cache[self::$locale][$group])) {
$file = self::find_file($group);
if ($file != false) {
include $file;
// Merge in configuration
if (!empty($lang) AND is_array($lang)) {
foreach ($lang as $k => $v) {
$mes[$k] = $v;
}
}
}
self::$language_cache[self::$locale][$group] = $mes;
}
if (isset(self::$language_cache[self::$locale][$group])) {
foreach (self::$language_cache[self::$locale][$group] as $k
=> $v) {
if ($key_lang == $k) {
return $v;
}
}
return $key_lang;
} else {
return 'Missing entry ' . self::$locale . '/' . $group;
}
}
}
?>
Nhiu ct cng lc
HTML Code:
<div class="container_12">
V tng padding nn rng cc khi cng tng theo. Tuy nhin ni dung ca khi First
vn ko trng qua ct th 4 m vn chim 3 ct
Ti sao khi Frist li dch qua phi 10px m ko nm ng v tr. Nguyn nhn l n ang
nm trong 1 khi Grid khc. V thuc tnh margin ca n khin n phi dch qua phi
10px. Ta khc phc = cch s dng class "alpha" v "omega"
HTML Code:
<div class="container_12">
<div class="grid_12">
<div class="grid_3 alpha" style="background:blue;">3 Ct</div>
<div class="grid_5" style="background:red;">5 Ct</div>
<div class="grid_4 omega" style="background:green;">4 Ct</div>
</div>
</div>
http://i1254.photobucket.com/albums/...mfnamoka/8.jpg
http://keynotekungfu.com/?ref=960
http://brandrichmedia.com/
http://nickfinck.com/
http://drupal.org/
http://5by5.tv/
Sau m ln v lu li vi ui l .xml
Trong trang html ta c 1 form cho php chn file xml(convert t file excel) cn nhp d
liu:
HTML Code:
<form action="b.php" method="post" enctype="multipart/form-data">
Select a file: <input type="file" name="upload" size="50" />
<input type="submit" name="send" value="Upload" />
</form>
>nodeValue;
$e = $r->getElementsByTagName("Cell")->item(4)>nodeValue;
$f = $r->getElementsByTagName("Cell")->item(5)>nodeValue;
//Khi to cu truy vn
$sql = "insert into media(song,singer,musician,cate
gories,album,url) values('" . $a . "','" . $b . "','" . $c . "','" . $d
. "','" . $e . "','" . $f . "')";
//Thc thi cu truy vn v kim tra kt qu tr v
if(mysql_query($sql) != FALSE){
$mess ="Thm d liu thnh cong";
}else{
$mess = "Thm d liu tht bi";
}
}
$first_row = FALSE;//Bin xc nh qua dng u tin
}
echo "<cente>$mess</center>";
}
}
?>
?>
</table>
<style type="text/css">
form{
text-align: center;
margin: 50px auto;
}
</style>
</head>
<body>
<form action="b.php" method="post" enctype="multipart/form-data">
Select a file: <input type="file" name="upload" size="50" />
<input type="submit" name="send" value="Upload" />
</form>
<table cellpadding="0" cellspacing="0" border="1" width="80%">
<tr>
<th>STT</th>
<th>Tn bi ht</th>
<th>Ca s</th>
<th>Nhc s</th>
<th>Th loi</th>
<th>Album</th>
<th>ng dn</th>
</tr>
<?php
$sql = "select * from media order by categories ASC";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0){
$stt = 0;
while($data = mysql_fetch_assoc($query)){
$stt++;
echo "<tr>";
echo "<td>$stt</td>";
echo "<td>$data[song]</td>";
echo "<td>$data[singer]</td>";
echo "<td>$data[musician]</td>";
echo "<td>$data[categories]</td>";
echo "<td>$data[album]</td>";
echo "<td>$data[url]</td>";
echo "</tr>";
}
}else{
echo "<tr><td colspan=7 align=center>Data empty</td></tr>";
}
?>
</table>
</body>
Ph cui cng th cng xong, y l ln th 2 vit li, hiz.. ny vit va xong nhp
xem li bi vit th b ging ra ngoi, lm mt sch :(( li phi ch vits li. Kt
qu nh hnh sau:
kho , bn no bit ri m bit cch vit hay hn th nh share cho mi ngi cng
hc hi nh.
Ai khng hiu th c th hi mnh hoc pm wa nick y h: thugianmotti :D
}else{
if(isset($url[1])){
$controller->{$url[1]}();
}else{
$controller->index();
}
}
}
}
?>
+file ny c tc dng t ng load controller v model khi ngi dng tng tc ti trang
+Lu :t tn file controller v model c phn u ging nhau,v tn file ging tn
class,v d user_Controller.php th class tng tng s l class user_Controller v model
s l user_Model.php class user_Model.Nh vy trong view s c th mc tng ng l
th mc user,
---Trang index s khi to Bootstrap nh sau :
PHP Code:
<?php
//define path
require_once("config/define_path.php");
require_once("config/define_database.php");
//end define path
require_once(__LIB_PATH."Session.php");
require_once(__LIB_PATH."Controller.php");
require_once(__LIB_PATH."View.php");
require_once(__LIB_PATH."Model.php");
require_once(__LIB_PATH."Bootstrap.php");
$bootstrap= new Bootstrap;
?>
$this->view->redirect();
}else{
$this->view->redirect("user/login");
}
}
}else{
$this->view->render("user/login");
}
}
public function logout(){
Session::set("login",false);
Session::unset_session("user");
$this->view->redirect();
}
}
?>
---File models/user_Model.php :
PHP Code:
<?php
class user_Model extends Model{
public $table="user";
public function __construct(){
parent::__construct();
}
public function login(){
$user=$_POST['user'];
$pass=md5($_POST['password']);
$where=array('user_name'=>$user,'pass'=>$pass);
$this->select($this->table,$where);
if($this->num_rows()==0){
return false;
}else{
return true;
}
}
}
?>
$i++;
}
if($currentPage != $pages){
// Nu khng trang cui th hin th nt Next
$next =$currentPage+1;
$next_middle = $middle+1;
echo "<span id ='list'><a href ='$_SERVER[PHP_SELF]?middle=
$next_middle&count=$count&page=$next'> Next </a></span>";
}
}
}
Code: demo_google.php
PHP Code:
<style>
#list{
border : 1px solid green;
padding:5px;
margin: 0px 3px;
}
#selected{
background: green;
}
a{
text-decoration: none;
}
a:hover{
color: white;
}
#list:hover{
background : green;
}
#list:hover a{
color:white;
}
</style>
<?php
require_once('phantrang_google.php');
$conn = new mysqli('localhost','root','','news_vmc');
//Mnh dng database ca bn news_vmc .
//Link down :
if(!isset($_GET['count'])){
// Lc m ra cng cha c $_GET['count']
$query = 'select * from tin';
$result = $conn->query($query);
$count = $result->num_rows;//Tr v s record trong table
//Dng mysqli
}
else{
$count = $_GET['count'];
}
//on code trn trnh vic lm li 2 cu truy vn mi khi chuyn tr
ang, n l cng //dng ca bin $count trong function pageList bn ki
a
$begin=$begin+1;
$end=$end+1;
}
}
}
//Xuat so trang hien thi
for($i=$begin;$i<=$end;$i++){
if($i==$current_page){
echo "[$i]";
}else{
echo "<a href='paging.php?total=$total&page=$i'> ".$i." </a>";
}
}
if($page<$total_page){
echo "<a href='paging.php?total=$total&page=".($current_page+1)."'>
NEXT</a>";
}
mysql_close($conn);
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$("a.link").click(function(){
id=this.getAttribute("id");
$.ajax({
type:"get",
url:"check.php",
data:"id="+id,
async:false,
success:function(kq){
$("#ketqua").html(kq);
}
})
$(":button").click(function(){
id=this.getAttribute("id");
alert("QHOnline.Info - Your link : "+id);
})
})
})
</script>
</head>
<body>
<a href='#' class="link" id="1">Link 1</a>
<a href='#' class="link" id="2">Link 2</a>
<a href='#' class="link" id="3">Link 3</a>
<div id="ketqua"></div>
</body>
</html>
Gii thch:
gi jquery ajax lng nhau, th chng ta phi cho d liu load trn mi trng
ng b. V s kin button ch xut hin khi chng ta click vo lin kt. Do vy, nu
cc bn async:true. Th d liu load bt ng b. V d nhin s kin di s
gi ng thi mc cho ajax mun lm g th lm.
K ti, s kin click vo nt button n c c khi no ?. N c c khi ngi
dng click vo link. V th. S kin nt button phi nm trong s kin click vo link
u tin. Nu t bn ngoi s kin click link th n s khng tm thy c
:button. V mi m ra lm g c :button cho jquery qut d liu.
Vy tng kt li:
PHP Code:
<script language="javascript" src="ajax.js"></script>
<select size="1" name="tl" class="title" onchange="if(this.value!=0){ja
vascript:loadXMLDoc(this.value,1);}">
<option value="0">--Chn th loi--</option>
<?php
require_once("includes/config.php");
$sql = "select * from theloai";
$result = mysql_query($sql);
while($data = mysql_fetch_array($result)){
echo "<option value='$data[idTL]'>$data[TenTL]</option>";
}
?>
</select>
<div id="ketqua"></div>
file ajax.js :
PHP Code:
// JavaScript Document
function obj(){
td = navigator.appName;
if(td == "Microsoft Internet Explorer"){
dd = new ActiveXObject("Microsoft.XMLHTTP");
}else{
dd = new XMLHttpRequest();
}
return dd;
}
http = obj();
function loadXMLDoc(id,p){
document.getElementById("ketqua").innerHTML = "ang x l...";
url = "process.php?id="+id+"&page="+p;
http.open("get",url,true);
http.onreadystatechange=process;
http.send(null);
}
function process(){
if(http.readyState == 4 && http.status == 200){
document.getElementById("ketqua").innerHTML = http.responseText
;
}
}
file proccess.php
code :
PHP Code:
<?php
$id = $_GET['id'];
$page = $_GET['page'];
require_once("includes/config.php");
$sql = "select * from tin where idTL=$id";
$result = mysql_query($sql);
$tongsorecord = mysql_num_rows($result);
$y = 1;
$start = ($page-1)*$y;
$tongsotrang = ceil($tongsorecord/$y);
if($tongsorecord == 0){
echo "Khng c tin no";
}else{
?>
<script language="javascript" src="ajax.js"></script>
<table align="center">
<tr>
<td class="title">STT</td>
<td class="title">Tiu </td>
<td class="title">Hnh</td>
</tr>
<?php
$stt = 0;
$sql1 = "select * from tin where idTL=$id limit $start,$y";
$result1 = mysql_query($sql1);
while($data1 = mysql_fetch_array($result1)){
$stt++;
echo "<tr>";
echo "<td>$stt</td>";
echo "<td>$data1[TieuDe]</td>";
echo "<td><img src='data/$data1[UrlHinh]' title='$data1[Tom
Tat]' /></td>";
echo "</tr>";
}
}
?>
<tr>
<td colspan="3">
<div id="pt">
<?php
for($i=1;$i<=$tongsotrang;$i++){
if($i == $page){
echo "<span class='active'>$i</span>";
}else{
echo "<a href='#' onclick='javascript:loadXMLDoc($i
d,$i);'>$i</a>";
}
}
?>
</div>
</td>
</tr>
</table>
PS : update bi vit :)
</body>
</html>
Bc 3 : To file jq-config.php
PHP Code:
define('DB_DSN','mysql:host=localhost;dbname=news_vmc');
define('DB_USER', 'root');
// Your MySQL username
define('DB_PASSWORD', ''); // ...and password
d: trong code thit lp khu vc lin kt ring cho trang <a href=#Anchor> c gii
thch v Anchor</a>
25. Lin kt n t nhng trang web c to ra cho mc ch seo cho trang khc hoc
nhng trang ng nghi ng +0
Nhng lin kt n t trang ny khng lm nh hng n trang ca bn nu nh bn
khng t links ca nhng trang ny vo website mnh. Google xem nh nhng lin kt
n t trang nay ngoi tm kim sot ca bn do bn khng b pht nhng trong mi
trng hp bn nn trnh xa nhng trang web c to ra cho mc ch seo hoc nhng
trang ng ng
26. Qu nhiu lin kt ra ngoi.
Google khng thch nhng trang c nhiu lin kt i ra ngoi, bi vy tt nht bn nn
gia s lin kt ra ngoi trn website mnh di 100 link. C nhiu link ra ngoi khng
to li ch no trong vic xp hng m thm ch cn gy nu hu qu ngc li
27. Qu nhiu lin kt hoc link spam -1
Rt c hi cho th hng ca bn khi bn c nhiu link n t mt website bi v n cho
thy bn ang mua link hoc t nht l spam link. Nu may mn th cng ch vi link
c tnh cho vic SEO ca bn thi.
28. t backlink cho nhng trang to ra cho mc ch SEO hoc nhng trang ng ng -3
Khng nh vic c link n t nhng trang to ra cho mc ch SEO hoc nhng trang
ng ng. Vic bn t li backlink trn website mnh cho nhng trang ny s khin
website ca bn b mt t kha hon ton. Bn cn phi nh k kim tra tnh trng ca
nhng trang t link trn trang ca bn. V d (Bn c to ra 5 blog wordpress hay
blogspot vi ni dung khng lin quan Seo cho mt t kha chnh n website bn, v
khi bn t li backlink cho 5 blog ny trong website bn s khin website bn ri vo
tnh trng mt t kha hon ton.)
29. Lin kt vng tr hnh -3
Lin kt vng xy ra khi trang A link n trang B, trang B link n trang C v trang C
link tr v trang A. l v d n gin v lin kt thnh vng v ngoi ra c nhng
trng hp khc na. Lin kt vng trong nh l mt loi lin kt trao i tr hnh v b
google pht nng
30. Lin kt link cho chiu rng pixel nh
Khi bn c t link trn website mnh c kch thc 1 pixel hoc chiu rng nh vy th
u ny c sem nh l v hnh vi con ngi v bn ang c gng qua mt b my tm
kim.
II.Metatags
31. <Description> metatag +1
Metatags th ang tr nn t quan trng hn i vi google nhng n vn c tnh. S
dng metatag <Description> vit m t cho website ca bn. Ngc li i vi Yahoo
v Bing n vn rt quan trng. i vi google i khi bn thy s xut hin ca m t
trong kt qu tm kim
32. <Keywords> metatag +1
Metatag <Keywords> khng c ch bi google nhng n vn c quan tm bi
Bing v Yahoo. Chiu di ca metatag <Keywords> khong 10 -20 t l tt nht. Khng
nn nhi nht t kha m bn khng c trong ni dung vic ca hi cho th hng ca
bn.1
33. <Language> metatag +1
Nu website ca bn c ngn ng c th th ng tab ny trng. Mc d cng c
search thng minh xc inh ngn ng trn trang ca bn thay v da vo s khai
bo trn th meta <language> nhng cng c search vn xem xt th ny.
34. <Refresh> metatag
Metatag refresh l mt cc chuyn lng khch t mt website n 1 website khc.
Ch lm vic ny nu bn cn duy chuyn trang web ca mnh n mt tn min mi v
bn cn tm thi chuyn hng khch truy cp. Nu s dng trong mt thi gian di n
s lm nh hng n bn xp hng ca bn. Trong mi trng hp s dung chuyn
hng 301 l tt nht.
III.Ni Dung
35. Ni dung c o +3
C nhiu ni dung (lin quan n ng cnh website v khc vi ni dung t website khc
c v tiu ln t ng) th s gip tng th hng ca bn 1 cch tht s
36. Tn s thay i ni dng
Thay i thng xuyn th c nh gi rt cao. S rt tt nu bn lin tc thm ni
dung mi cho website
37. Kch thc ca t kha : +2
Khi 1 t kha trong vn bn c font ln nhng t cn li u khin cho n ng ch
hn do n quan trng hn phn cn li ca on text. Cch tnh im ny vn p dng
53. Flash -2
B tm kim khng nh ch mc cho ni dung Flash bi vy bn lun nh t ni dung
cho th <alt>
54. Flash trn trang ch -3
Cch ny dng nh hin ti khng cn dng. Nhng c mt Flash trn trang ch v
khng c c HTML th xem nh l bn chng Seo g c.
V. Domains, URLs, Web Mastery
55. Url cha nhiu thng tin +3
u ny rt quan trng t bit i vi Yahoo v Bing
56. Kh nng truy cp web +3
Mt vn c bn m bn thng b qun. l nu nh website ca bn (hoc mt s
trang trong website) b h link, hoc li 404, hoc t mt khu bo mt th n gin l
nhng trang s khng c nh ch mc.
57. Sitemap +2
Rt tt nu bn c sitemap cho website v b tm kim c bit quan tm loi file ny.
Bn c th lm theo dnh ang HTML hoc lm theo nh dng ca google
58. ln website +2
B tm kim rt thch nhng website ln , cng ln cng tt. Khng c website no b
pht v c trn 10 000 trang c.
59. Tui ca website +2
Trang web c thi gian tn ti lu th c nh gi cao hn l mt website mi c
thnh lp.
60. Giao din trang +2
Giao din trang cung quan trng cho th hng bi v khi trang ph hp vi 1 giao din,
iu ny gip tng th hn ca tt c cc trang lin quan n giao din ny.
61. V tr tp tin trong trang web +1
V tr tp tin trong website cng gn vi th mc gc c xu hng xp hng tt hn so
vi tp tin cch xa th mc gc
---file js ajax.js :
PHP Code:
$(document).ready(function(){
$("a.pt").click(function(){
var page=$(this).attr("title");
var start=this.id;
$.ajax({
type : "GET",
url : "index.php?page="+page+"&start="+start,
datatype: "html",
beforeSend: function(){
$('#load').html("LOADDING...");
},
success: function(html){
$('#load').text('');
$('#kq').html(html);
}
});
})
})
N tht s l v b phi ko ?
Thay v lm nh vy, chng ta lm th ny vy , ci ny s run up 100% faster , ci ny
ng Google bo m y
PHP Code:
$doc->name ="Emiko";
$n = $doc->name;
$b;
. Hy thay i
echo"<br />";
$b= new SubtractionClass;
$x=10;$y=7;
echo $b->operationName($x,$y);
$b->setValue($x,$y);
$b->printOut();
?>
Kt qu:
Day la phep toan Tong: 7+7=14
Day la phep toan Hieu: 10-7=3
y l v d mnh vit trong phm vi phi kin thc hn hp ca mnh mong cc bn
ng gp kin.:)
---------------------admin/
-----------------------------controllers/
-----------------------------modles/
-----------------------------views/
-----------------------------forms/
-----------------------------blocks/
---------------------shopping/
-----------------------------controllers/
-----------------------------modles/
-----------------------------views/
-----------------------------forms/
-----------------------------blocks/
---------------------news/
-----------------------------controllers/
-----------------------------modles/
-----------------------------views/
-----------------------------forms/
-----------------------------blocks/
---public/
---------templatest/
---------------------admin/
-----------------------------images/
-----------------------------css/
-----------------------------js/
-----------------------------flash/
---------------------shopping/
-----------------------------images/
-----------------------------css/
-----------------------------js/
-----------------------------flash/
---------------------news/
-----------------------------images/
-----------------------------css/
-----------------------------js/
-----------------------------flash/
---------upload/
---library/
---.htacess/
---define.php/
---index.php/
---y l m hnh mnh ang s dng nhn vo cu trc chc cc bn hiu ngha cc
th mc ri.
---File Bootstrap.php :
PHP Code:
<?php
class Bootstrap{
public static $module = NULL;//ly tn module hin ti
public static $controller = NULL;//ly tn controller hin ti
public static $action = NULL;//ly action hin ti
public static $id = NULL;//ly id hin ti
private static $instance = NULL;
public function __construct(){
if(self::$instance == NULL){
self::$instance = new Bootstrap;
}
return self::$instance;
}
public static function run(){
Session::__init();
if(isset($_GET['url'])){
$url = $_GET['url'];
$url = rtrim($url,"/");
$url = explode("/",$url);
self::$module = $url[0];
}else{
self::$module = 'default';
}
if(isset($url[1])){
self::$controller = ucfirst($url[1]);//bien doi chu cai dau
tient hanh chu hoa
}else{
self::$controller = 'Index';
self::$action = 'IndexAction';
}//end if isset $url[1];
//ly file controller hin ti
$modules_path = MODULES_PATH . self::$module;//duong dan toi mo
dules hien tai
$name_controller = self::$controller . 'Controller';
$file_control = MODULES_PATH . self::$module . '/controllers/'
. $name_controller . '.php';
if(file_exists($file_control) && file_exists($modules_path)){
require_once($file_control);
}else{//chay controller error
$file_control = MODULES_PATH . 'default/controllers/ErrorC
ontroller.php' ;
$name_controller = 'ErrorController';
require_once($file_control);
}
$c = new $name_controller;
$c->LoadModel(self::$controller);//auto load model
if(isset($url[2])){
if(isset($url[3])){
self::$id=$url[3];
self::$action = ucfirst($url[2]).'Action';
$c->{self::$action}(self::$id);
}else{
self::$action = $url[2].'Action';
$c->{self::$action}();
}
}else{
$c->IndexAction();
}
}
}
?>
---
Tm hiu th vin
Php_filter
A.PHP_FILTER l g ?
Hin nay, hu ht mi ng dng u c s dng d liu t nhng ngun ngoi khng an
ton bao gm :
Cookies
Bin server
Cc kt qu tr v t database
B.CCH S DNG
Kiu lc:
Kiu lc ny dng cho php hoc khng cho php mt s k t trong chui
Lun tr v chui .
Cc loi FILTER_SANITIZE cn nh :
Cc loi FILTER_VALIDATE cn nh :
filter.php
PHP Code:
<?php
if(filter_has_var(INPUT_POST,'comments')){
echo ' C field tn l comments trong form input ';
}
else
echo 'Khng c field tn comments trong form input<br/>';
$name = filter_input(INPUT_POST,'name',FILTER_SANITIZE_STRING);
$options = array('options'=>array('min_range' =>18, 'max_range'
=>80));
if(!filter_input(INPUT_POST,'age',FILTER_VALIDATE_INT,$options)
){
echo ' Tui ca bn phi >18 v < 80 <br/>';
}
else{
$age = filter_input(INPUT_POST,'age',FILTER_VALIDATE_INT,
$options);
}
if(!filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)){
echo ' Email sai format<br/>';
}
else{
$age = filter_input(INPUT_POST,'email',FILTER_VALIDATE_EM
AIL);
}
/*on code trn kim tra input ca ngi dng, nu email v tui hp l
th mi tin hnh gn vo bin, nu hok th xut li.
Hm filter_input y c th dng INPUT_GET thay cho INPUT_POST nu me
thod ca bn l GET.
*/
?>
LIDATE_EMAIL) );
$result = filter_input_array(INPUT_POST, $array);
if($result['name'] && $result['age'] && $result['email']){
extract($result); //Hm ny ct mng khng tun t,
tn ca kha s l bin cha gi tr kha
}
var_dump($name);
var_dump($age);
var_dump($email);
Cc bn th tr li cc cu hi sau nh :
1/ Filter l g ? Ti sao phi dng filter ?
2/ dng Filter cn nh cc hm no ?
3/ Kiu lc c my loi ? Trong mi loi th c cc loi FILTER_ no ?
4/ Cch s dng cc hm trong filter .
PHP Code:
<?php
class DB_MySQL{
private $db_host = "localhost"; //Khai bo thng tin host database
private $db_user = "root"; //Khai bo thng tin username database
private $db_pass = ""; //Khai bo thng tin password database
private $db_name = "test"; // Khai bo thng tin name database
private $connection;
private $result = null; //Thuc tnh result tr v kt qu ca quer
y.
private $magic_quotes_active;
private $real_escape_string_exists;
public function __construct(){
$this>openConnect(); // T ng m kt ni CSDL khi gi n class
$this->magic_quotes_active = get_magic_quotes_gpc();
$this>real_escape_string_exists = function_exists( "mysql_real_escape_string
" );
}
//M kt ni CSDL
public function openConnect(){
$this->connection = mysql_connect($this->db_host, $this>db_user, $this->db_pass);
if (!$this->connection){
die("Database connection failed: " . mysql_error());
}
else{
$db_select = mysql_select_db($this->db_name, $this>connection);
if(!$db_select){
die("Database selection failed: " . mysql_error());
}
}
}
//ng kt ni CSDL
public function closeConnect(){
if ($this->connection)
{
mysql_close($this->connection);
unset($this->connection);
}
}
//Phng thc chng SQL Injection
public function sqlQuote( $value ){
//Kim tra xem version PHP bn s dng c hiu hm mysql_real_e
scape_string() hay ko
if ($this->real_escape_string_exists) {
//Trng hp s dng PHP v4.3.0 tr ln
//PHP hiu hm mysql_real_escape_string()
if( $this->magic_quotes_active ) {
//Trong trng hp PHP h tr hm get_magic_quotes_g
pc()
//Ta s dng hm stripslashes b qua cc du slashes
$value = stripslashes( $value );
}
$value = mysql_real_escape_string( $value );
}
else {
//Trng hp dng cho cc version PHP di 4.3.0
//PHP khng hiu hm mysql_real_escape_string()
if( !$this->magic_quotes_active ){
//Trong trng hp PHP khng h tr hm get_magic_quote
s_gpc()
//Ta s dng hm addslashes thm cc du slashes vo
gi tr
$value = addslashes( $value );
}
// Nu hm get_magic_quotes_gpc() active c ngha l cc
du slashes tn ti ri
}
return $value;
}
//Chy cu truy vn query
public function query($sql){
$this->result = mysql_query($sql, $this->connection);
if (!$this->result){
$output = "Database query failed: " . mysql_error() . "<br
/><br />";
die($output);
}
return $this->result;
}
//Ly s record d liu mng trong CSDL thng qua cu truy vn quer
y
public function fetch_array(){
if ($this->result){
$rows = array();
$rows = mysql_fetch_array($this->result);
}
return $rows;
}
//m s record trong CSDL thng qua cu truy vn query
public function num_row(){
if($this->result){
$num = null;
$num = mysql_num_rows($this->result);
}
return $num;
}
}
?>
Cch s dng:
PHP Code:
$username = $_POST['username'];
$password = $_POST['password'];
$db = new DB_MySQL;
$sql = "SELECT * FROM user WHERE username='".$db>sqlQuote($username)."' AND password='".$db->sqlQuote($password)."'";
$db->query($sql);
.......................
$db->closeConnect();
C th chng SQL Injection 1 cch linh hot hn bng cch s dng sqlQuote
thit lp cc gi tr input trc khi a n vo cu truy vn sql.
return $info;
}
?>
<ul style='list-style:none;'>
<li><a href='?mod=xa-hoi'>X Hi</a></li>
<li><a href='?mod=the-gioi'>Th Gii</a></li>
<li><a href='?mod=kinh-doanh'>Kinh Doanh</a></li>
<li><a href='?mod=van-hoa'>Vn Ha</a></li>
<li><a href='?mod=the-thao'>Th Thao</a></li>
</ul>
<?
$file='http://vnexpress.net/rss/gl/xa-hoi.rss';
switch($_REQUEST['mod'])
{
case "xa-hoi":
$file='http://vnexpress.net/rss/gl/xa-hoi.rss';
break;
case "the-gioi":
$file='http://vnexpress.net/rss/gl/the-gioi.rss';
break;
case 'kinh-doanh':
$file='http://vnexpress.net/rss/gl/kinh-doanh.rss';
break;
case 'van-hoa':
$file="http://vnexpress.net/rss/gl/van-hoa.rss";
break;
case 'the-thao':
$file='http://vnexpress.net/rss/gl/the-thao.rss';
break;
default:
$file='http://vnexpress.net/rss/gl/xa-hoi.rss';
break;
}
$dom=new DOMDocument('1.0','utf-8');//tao doi tuong dom
$dom->load($file);//muon lay rss tu trang nao thi ban khai bao day
$items = $dom>getElementsByTagName("item");//lay cac element co tag name la item va
gan vao bien $items
foreach($items as $item)//lap
{
$titles=$item>getElementsByTagName('title');//lay cac element co tag name la title v
a gan vao bien $titles
$title=$titles>item(0);//lay ra gia tri dau tuien trong array $titles
$descriptions=$item->getElementsByTagName('description');
$des=$descriptions->item(0);
$links=$item->getElementsByTagName('link');
$link=$links->item(0);
$pubDates=$item->getElementsByTagName('pubDate');
$pubDate=$pubDates->item(0);
?>
<table width="800" border="1" align=center bgcolor=#e5eef2>
<tr>
<td style="color:#FF0000; font-weight:bold; textdecoration:none"><a href="<? echo $link>nodeValue ;?>" /><? echo $title->nodeValue ?></td>
</tr>
<tr>
<td>
<?php
echo $pubDate->nodeValue;
echo $dec->nodeValue;
?>
</td>
</tr>
<tr>
<td><font face=arial size=2>
<?php
$url=$link->nodeValue;
$start="<div id=\"content\">";
$end="<div class=\"tag-parent\">";
$img_search= "/Files";
$img_show="http://vnexpress.net/Files";
$extra='<META HTTP-EQUIV="Content-Type" Content="texthtml; charset=UTF8"><link href="/Resource/Common/default.css" rel="stylesheet" type="tex
t/css">';
echo getdata($url,$start,$end,$img_search,$img_show,$extra);
?>
</font></td>
</tr>
</table>
<?
}
?>
Khng hiu sao khi lm localhost th chy ngon va upload ln host thi khng c g
^^.Bc no bit ti sao khng,Chc do host ri ln khng demo dc,chu kh to file
php chy trn localhost nha
Ai c cch ly tin no hay post ln anh em tham kho nh
}
?>
==> Tm chui phppro hoc php pro. Kt qu l tn ti.
+ Du * qui nh: khng tn ti, hoc nu c th c th c nhiu
<?php
if (preg_match(/php(\s)*pro/i, PHP pro is the web scripting language of choice. And I
choice PHP)) {
echo A match was found.;
} else {
echo A match was not found.;
}
?>
==> Tm chui phppro hoc php pro ( gia c th c nhiu khong trng). Kt qu l
tn ti.
+ Du + qui nh: phi tn ti t 1 tr ln.
<?php
if (preg_match(/php(\s)+pro/i, PHPpro is the web scripting language of choice. And I
choice PHP)) {
echo A match was found.;
} else {
echo A match was not found.;
}
?>
==> Tm chui php pro ( gia phi c t 1 khong trng tr ln). Kt qu l khng tn
ti.
+ Cp du [] lit k
<?php
if (preg_match(/[_,]php/i, _PHP is the web scripting language of choice)) {
echo A match was found.;
} else {
echo A match was not found.;
}
?>
==> Tm chui _php hoc ,php . Kt qu l tn ti
+ A-Z, a-z , A-z qui nh mt k t vit hoa, vit thng, tt c. Phi i km vi du []
<?php
if (preg_match(/[a-z]php/i, aPHP is the web scripting language of choice)) {
echo A match was found.;
} else {
echo A match was not found.;
}
?>
==> Kt qu l tn ti
+ 0-9 qui nh mt k s
<?php
if (preg_match(/[0-9]php/i, _PHP is the web scripting language of choice)) {
HTML Code:
<form onsubmit="return false;">
<?php
$conn=@mysql_connect("localhost","root","root");
@mysql_set_charset('utf8',$conn);
@mysql_select_db("nhac",$conn);
?>
C g thc mc c comment hn !
Tn mn v ECHO
Chc cc bn chng bao gi c Document v echo u nh? Nhng hm nay mnh e
rng cc bn s phi kh bt ng, v ti sao mnh li vit bi ny, tht s th mnh cng
hi bt ng khi v tnh c phi document v n trn php.net
// Cch 2
echo "Hello \"QHO Solution\"";
// -------------- //
R rng cch 1 hay hn cch 2 ng ko no?
'<div>';
"<p>$a</p>";
'<input type="checkbox" name="abc" value="'.$b.'" />';
'</div>';
// on trn c rt gn li thnh
echo <<<END
<div>
<p>$a</p>
<input type="checkbox" name="abc" value="$b" />
</div>
END;
// R rng cch vit di gn hn cch trn, ng thi code HTML c t
ab vo d nhn hn
---------------Trong nhng trng hp trn, mnh 'khoi' nht l ci th 5 ^^, tht bt ng khi
tnh c c thy n, 1 cht chia s cho nhng bn cha bit
test_2.php
PHP Code:
<table width=100%>
<?php
$size_1=GetImageSize('images/images.jpg');
$size_1[0]=$size_1[0]/5;
$size_1[1]=$size_1[1]/5;
$size_2=GetImageSize('images/name.jpg');
$size_2[0]=$size_2[0]/5;
$size_2[1]=$size_2[1]/5;
$name=$_GET['name'];
if(strstr($name,'phpMyAdmin')===false)
{
$file_0="folder/$name/";
$dir=opendir($file_0);
}
else
{
$file_0="$name/";
$dir=opendir($name);
}
while(($file=readdir($dir))!==false)
{
$file_or_folder="$file_0/$file";
echo "<tr><td>";
if(is_dir($file_or_folder)
&& $file!='.'
&& $file!='..')
{
$temp=$file;
$file=$file_0."$file";
$target="test_2.php?name=".$file;
echo "<a href=\"".$target."\"><img src=\"image
s/images.jpg\" width=\"".$size_1[0]."\" height=\"".$size_1[1]."\"/>$tem
p</a></td>";
}
if(!is_dir($file_or_folder) && $file!='.' &&
$file!='..')
echo " <img src=\"images/name.jpg\" width=\"
".$size_2[0]."\" height=\"".$size_2[1]."\"/>$file</td>";
}
closedir($dir);
?>
</table>
trn dng : opendir() : m th mc, readdir() : c th mc, is_dir(): kim tra xem th
mc l folder hay file (folder return true, not : return false) .
Trong 1 folder n c ci foldername && filename l '.' vi '..' . Mnh hok bit 2 a ny
u ra nhng m chn n ngay folder th n li xut hin di dng file v ngc li nn
mnh chn 2 ci lun ( if (is_dir... && $file!='.' && $file!='..') ) .
Test 1.php :
Mnh download hnh v n to nn mnh dng hm GetImageSize() ly width ( size[0])
v height( size[1]) ri chia 5 >< .
Lu l kim tra c phi folder hay hok, mnh phi chn vo trc tn ca file or
folder tn th mc cha thnh ng dn y . Nn dng bin $file_or_folder t
tin t .
Test 2.php:
Nguyn l ca test_2 .php l n chy lp li, t test_2.php s chy tp test_2.php thng
qua phng thc $_GET . Nn mnh phi kim xem, $name y c tin t cha (
nu c ri tc l test_2.php bt u lp) . Nu cha th phi chn tin t vo ri mi
opendir().
C cu lp : ly $temp gi ni dung $file lt xut ra mn hnh .
Sau $file s dc chn tin t $file_0 vo . Ri gn $target ( ng tr link ) = $file
var_dump($result);
//Tr v FALSE v hm strpos phn bit hoa thng
$result = strpos($string, 'is');
var_dump($result);
//Tr v 3
Dng: di chui s b th
V d :
PHP Code:
$string = 'This is a test of substr_replace ';
$result = substr_replace($string, 'replaced', 3,4);
var_dump($result);
//Xut Thireplaced a test of substr replace
$result = substr_replace($string, 'replaced', 3, -4);
var_dump($result);
//Xut Thireplacedace
$result = substr_replace($string, 'replaced', 3,0);
//Xut Thireplaces is a test of substr_replace
$result = substr_replace($string, 'replaced',-3,5);
//Xut This is a test of substr replareplaced
";
VD:
PHP Code:
$string = ' This is some text ';//chui c ucfirst sn ri
$string_lower = strtolower($string);
// this is some text
$string_upper = strtoupper($string);
// THIS IS SOME TEXT
$string_first = ucwords($string);
// This Is Some Text
strrev(string): o chui
VD:
PHP Code:
$string = ' ABC';
var_dump(strrev($string));
//Xut BCA
II/Khi to mng
khi to mng chng ta dng t kha array
Trong PHP c 3 cch khi to mng nh sau :
1/ Khi to 1 mng rng, sau mi set gi tr
2/ Khi to 1 mng vi 1 s gi tr ban u, sau thm gi tr mi vo
3/ Khi to mng v set full gi tr cho mng .
Mng tun t
Mng a chiu
1/ Mng tun t
Mng tun t l mng m cc kha ca n c nh theo s . V tr u tin ca mng
lun l 0
V d : $array_name = array('a', 'b', 'c', 'd');
trn, ly gi tr 'a' , ta dng c php : $array_name[0];
Tng t, ly gi tr 'b', 'c', 'd' : $array_name[1], $array_name[2], $array_name[3]
a/ Khi to mng tun t:
i/ To mng rng ri thm gi tr
$array = array();
$array[] = a;
$array[] = b ;
ii/ To mng sau thm gi tr mi vo
$array = array(a);
$array[] = array(b);
iii/ To mng full gi tr
$array = array(a,b);
Lu : Nu mun khi u mng hok phi l 0 m l 1 chng ta lm nh sau :
$array = array('1'=>'a', 'b', 'c' );
$array_name[$i] <
br/>";
}
// Code xut tng gi tr ca mng
FOREACH
foreach($array_name as $value){
// Vit code thao tc vi phn t mng y
}
Gii thch :
Hm foreach cng duyt tng phn t ca mng, vi mi phn t n i qua, n s gn gi
tr ca phn t cho bin $value .
V d :
PHP Code:
$i = 0;
foreach($array_name as $value){
$i++; //Tng ln 1 mi khi foreach duyt qua 1 phn
t
echo "Gi tr ca phn t $i l :
$value <br/>";
}
// Code xut tng gi tr ca mng
PHP Code:
foreach($array_ktt as $value){
echo " $value | ";
}
//Code trn dng thao tc ch vi cc GI TR ca mng khng tun t
foreach($array_ktt as $key=>$value){
echo " $key => $value | ";
}
//Code trn dng thao tc vi c GI TR v KHA ca mng khng tun
t
WHILE :
while(list($key,$value) as each($array_ktt)){
//Code y
}
Code trn c ngha: vi mi gi tr m while duyt qua, kha v gi tr ca $array_ktt ln
lt c gn vo $key v $value .
while($element as each($array_ktt)){
//Code y
}
Code trn c ngha: vi mi gi tr m while duyt qua, phn t ca $array_ktt ln lt
c gn $element . $element y ng vai tr nh l 1 ci mng khng tun t lu
$key v $value ca mi $array_ktt m while duyt qua .
V d :
PHP Code:
while($element as each($array_ktt)){
echo $element['key'];
echo ' - ';
echo $element['value'];
echo '<br/>';
}
//Code trn c ngha: vi mi gi tr m while duyt qua, phn t ca $
array_ktt ln lt c gn $element . $element y ng vai tr nh
l 1 ci mng khng tun t lu kha v gi tr ca mi $array_ktt m
while duyt qua .
3/ Mng a chiu
Hnh dung 1 ci t to c cc ngn ko, trong 1 s ngn ko li chia thnh 2-3 ci ngn
ko nh khc . Hay cng c th ni l : trong ngn ko c 1 chic t nh khc
V d:
$multi_array_tt = array('a', 'b', array('c','d'),'e');
$multi_array_ktt = array('a'=>'a_123', 'b'=>'b_123',
'small_array'=>array('c'=>'c_123','d'=>'d_123'),'e '=>'e_123');
Vy truy cp vo ngn ko ci t nh y, ta phi: Truy cp vo ngn ko ca t ln
cha t nh, sau truy cp vo ngn ko ca t nh .
echo " $multi_array_tt[2][0] "; //Xut ra 'c'
// Truy cp vo mng l phn t th 3 ca mng $multi_array_tt, sau ly phn t th 1
ca mng y ra .
'c1'),
array('a2', 'b2'
, 'c2') );
// Bn hnh dung mng $multi_array_test nh trn l 1 table c 3 ct v
3 dng
for($row = 0; $row <3; $row++){
for($column =0; $column < 3; $column++){
echo '|'.$multi_array_test[$row][$column];
}
echo '<br/>';
}
Lu : hm ny sp xp theo th t A<Z<a<z .
Sort theo quy lut t nhin : tc l 1<2<3<20....
natsort($array) : phn bit ch hoa v ch thng
natcasesort($array) : hok phn bit ch hoa v ch thng
VD:
PHP Code:
$array = array('a1','a2','a11','a22', 'A24');
sort($array);
var_dump($array);
natsort($array);
var_dump($array);
natcasesort($array);
var_dump($array);
/* Nhn c kt qu sau :
array
0 => string 'A24' (length=3)
1 => string 'a1' (length=2)
2 => string 'a11' (length=3)
3 => string 'a2' (length=2)
4 => string 'a22' (length=3)
array
0 => string 'A24' (length=3)
1 => string 'a1' (length=2)
3 => string 'a2' (length=2)
2 => string 'a11' (length=3)
4 => string 'a22' (length=3)
array
1 => string 'a1' (length=2)
3 => string 'a2' (length=2)
2 => string 'a11' (length=3)
4 => string 'a22' (length=3)
0 => string 'A24' (length=3)
/*
=>$array1_reverse gi l array(c,a,b)
Nh ni phn 1 , nhiu khi chng ta phi thay i v tr con tr mng thao tc
theo mun . lm iu ta dng cc hm :
Prev() : li con tr 1 phn t
next(): tin con tr 1 phn t,
reset(): reset con tr v v tr 0
end(): a con tr n v tr cui
Lu : Cc hm trn u tr v gi tr ca ni m con tr ang ng
current() : xut gi tr ca v tr hin ti ca con tr
each() : tr v key v gi tr ca v tr con tr ang ng, sau tin con tr ln 1 phn t
.
Hm m phn t mng :
Count($array)
Array_count_values($array): Hm ny m s ln xut hin ca 1 gi tr trong mng .
Tr v kiu d liu mng
Vd :
PHP Code:
<?php
$array = array('a','b','c','d','a','c');
echo current($array); // Xut 'a' do khi mi to, con tr nm v
tr u
echo next($array); // Xut 'b'
echo '<br/>';
$value = end($array); //Chuyn con tr v cui( trc 'c')
while($value){
echo " $value ";
$value = prev ($array); //Sau mi ln lp, li con tr 1 phn t
}
echo '<br/>';
echo reset($array); //a con tr v v tr u
$each = each($array); //Ly gi tr v kha ca v tr u, tr v
kiu d liu mng
var_dump($each);
var_dump(array_count_values($array));// Tr v kiu d liu mng .
?>
V d :
PHP Code:
$array = array('a'=>'a_123','a'=>'b_123','c'=>'c_123' , '1'=>
'INVALID');
$array_1= array('a'=>'a_123', 'd'=>'d_123', 'e'=>'e_123');
$a = 4;
(1)extract($array,EXTR_PREFIX_SAME,'abc');
//To bin $a = 'a_123' v $abc_a = 'b_123'
var_dump($a);
var_dump($abc_a);
(2)extract($array,EXTR_PREFIX_ALL,'abc');
//To bin $abc_a = 'b_123' ( b ghi )v $abc_c = 'c_123'
var_dump($abc_a);
var_dump($abc_c);
(3)extract($array_1,EXTR_PREFIX_IF_EXISTS,'ade');
//To bin $ade_a = 'a_123' v $d = 'd_123' v $e= 'e_123'
var_dump($ade_a);
var_dump($d);
var_dump($e);
(4)extract($array,EXTR_PREFIX_INVALID,'abc');
//To bin $abc_12 = 'INVALID' v $a= 'b_123' ( b ghi ) , $c = '
c_123'
var_dump($a);
var_dump($abc_12);
var_dump($c);
(5) extract($array,EXTR_REFS);
//To bin $a = 'b_123' v $c = 'c_123'
var_dump($c) ; //Xut c_123
$c =5;
var_dump($array['c']) // Xut ra 5 => Thay i gi tr trong
mng
Tc l code:
PHP Code:
if($_POST['user'] !=NULL){
$user = $_POST['user'];
}
else
echo 'Ban chua nhap ten ';
if($_POST['pasword'] !=NULL){
$pass = $_POST['password'];
}
else
echo 'Ban chua nhap password ';
if($user && $pass ) { }
Ta dng code :
PHP Code:
if(isset($_POST['ok'])){
// ok l tn trng submit <input type = submit value = login
name = ok />
//X l form y
}
C th l :
PHP Code:
$_SESSION['username'] = $username ( bin $username ny ly t form )
$_SESSION['level'] = $level
$_SESSION['u_id'] = $user_id
//C 2 $level v $user_id chng ta phi ly t database v .
//S d to 3 ci $_SESSION nh th v sau ny trong script khc chng
ta cn bit l ai ang truy cp, u_id l g ?
Ti tt c cc file trong trang admin tr login , bn phi kim tra xem ngi
dng c phi l admin khng ? Nu phi th cho truy cp, khng phi th v
trang login.php .
Vy chng ta c 1 code dng rt nhiu trong phn admin l:
PHP Code:
if($_SESSION['level'] != '2'){
header('localtion: login.php');
exit();
}
1 s lu vi cc file edit:
VD:
....
PHP Code:
<tr>
<td>Full</td>
<td><textarea name='txtfull' cols='40' rows='15'><?php echo $da
ta2['news_full'];?></textarea></td>
</tr>
<script type="text/javascript">
CKEDITOR.replace( txtfull );
</script>
....
=> Full s c b son tho cho ngi dng
DOWNLOAD CKEDITOR: http://www.mediafire.com/?ah85w2j03ddjdm6
HNG DN CODE
TRANG BN SCH
Tip theo mnh xin hng dn cc bn hnh dung cch code 1 trang bn sch .
A. M t ng dng bn sch
Nu l khch ( hok ng nhp ) th s c :
Chn chuyn mc sch, khi click vo chuyn mc th lit k cc sch c trong chuyn
mc . Khi click vo sch no th lit k thng tin ca sch gm tc gi , ISBN, ngy xut
bn, gi tin , v.v . Ti y cho php ngi dng thm sch vo gi hng . Sau khi thm
vo gi hng c th to nhiu option cho ngi dng la chn , hoc l thanh ton -> cho
ngi dng nhp thng tin ship sch , hoc l tip tc mua sch .
Bc thanh ton c 2 giai on :
1/ Nhp thng tin khch hng, a ch thanh ton, a ch ship sch, v.v . ng dng nh,
chng ta a ch khch hng l ni ship sch lun cho tin
2/ Chn phng thc thanh ton, in m th ( v nh th CREDIT CARD, VISA
CARD, v.v..)
Vy, nu ngi dng click thanh ton, v sau hok thanh ton tip bc 2 m chn tip
tc mua sch -> thm vo gi hng-> thanh ton <<<< Khng yu cu ngi dng nhp
thng tin giai on 1 na
Ti trang hin th gi hng : cho php ngi dng thay i s lng sch, v click nt
Save cp nht, nu ngi dng nhp 0 th sch s c b .
1 s lu :
Khi ngi dng ang xem list sch trong chuyn mc A th nn c ng link dn khch
qua trang list chuyn mc ng dng xem list sch ca chuyn mc khc .
Ti trang xut thng tin sch c th, th nn c 1 ng link dn khch qua trang list sch
ca chuyn mc cha sch hin ti .
Gi : Ti 2 trang trn u c 1 nt : Continue Shopping nhng chc nng khc nhau
.
Nu ng nhp di quyn user : ch khc khch ch bc thanh ton hok c giai
on 1 .
// C th b hn user, ch admin v khch thoi cng c
Nu ng nhp di quyn admin :
PHP c bn, hiu r mng, hiu r GET POST trong form HTML
PHP SESSION
Database MySQL select, delete, insert, update, v.v c bn
SQL c bn
Bit cch layout ghp header, footer, body
Quy trnh :
Chng ta cn cc file sau :
(0) login.php : ng nhp
(1)Index.php : list cc chuyn mc
(2)List_books.php : list cc sch trong chuyn mc
(3)Book_info.php : xut thng tin sch
(4) Show_cart.php: hin th gi hng
(5) check_out.php : hin th form ngi dng nhp thng tin .
(6) purchase.php : x l d liu nhn t ngi dng ( t giai on 1)
(7) process.php: x l d liu nhn t ngi dng ( t giai on 2 )
(8) logout.php : ng xut
Folder admin :
Ad(0) admin.php : list cc quyn ca admin
Ad(1) delete_cate.php : xa chuyn mc
Ad(2) delete_book.php: xa sch
Ad(3) edit_cate.php : sa chuyn mc
Ad(4) edit_book.php: sa sch
Ad(5) insert_cate.php: thm chuyn mc
Ad(6) insert_book.php : thm sch
Ad(7) list_users.php : list cc user v level
Ad(8) edit_user.php : chnh sa
Ad(9) delete_user.php : xa user
Ti cc trang lien quan n admin, lun c s kim tra xem ngi ang truy cp
c phi admin hay khng v lun c link dn admin v li Ad(0)
Database thit k nh th no ?
To DATABASE books vi cc table sau:
USER(user_id, username, password, level )
BOOKS(isbn, author, title, cate_id, price, description )
CAGORIES ( cate_id, cate_name)
CUSTOMERS( cus_id, cus_name, cus_address, cus_city, cus_state, cus_zip,
cus_country)
ORDERS( order_id, cus_id, amount , date , confirm )
ORDER_ITEMS (order_id, order_items, item_price, quantity)
Gii thch :
Mt s iu quan trong :
1/ Code kim tra c phi l admin hay khng v code kt ni database c s dng rt
nhiu nn vo 2 file b vo th mc includes sau ny dng require_once() xi li .
2/ Nu l user => n cc tnh nng nh xa, sa ,v.v . V th trong mi script (1)->(3)
chng ta phi kim tra, nu l admin th hin, hok l admin th n .
3/ Nu l admin th ng cho admin mua hng ^^ .
4/ Khi xc nhn 1 ng l user ( c th l admin ), cp cho ng 1 phin lm vic gm
username, level v u_id .
1 s gi :
Hin th gi hng : gi s ng mua add sch A vo gi, kim tra xem c tn ti sch A
trong gi hok, nu c th tng ln 1 , nu hok th thm sch A vo .
Code :
PHP Code:
if(!isset($_SESSION['cart']){
$_SESSION['cart'] = array();
// Nu ngi dng cha mua hng, to 1 session l 1 mng
// Mng ny ch cha
(isbn) => (quantity)
}
if(isset($_SESSION['cart'][$isbn])){
$_SESSION['cart'][$isbn] ++;
// Nu tn ti sch A, th tang ln 1
}
else
$_SESSION['cart'][$isbn] = 1;
//Ngc li thm vo sch A
}
// Code hin th gi hng y
<tr><td>Username: </td>
<td><input type= 'text' name = 'username' value= "<?php echo $e
dit ? $user['username'] : '' ;?> " /></td>
</tr>
<tr>
<td>Password: </td>
<td><input type= 'password' name = 'password' /></td>
</tr>
</table>
</form>
!=0
){
if($_POST['txtname'] == NULL){
echo 'Bn cha nhp username<br/>' ;
}
else
$name = $_POST['txtname'];
if($_POST['txtpass'] == NULL){
echo 'Bn cha nhp password<br/>' ;
}
else
$pass = $_POST['txtpass'];
if($name && $pass ) {
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('books');
$sql = "select * from user where username = '$name' and pas
sword = '$pass' ";
$result = mysql_query($sql);
if(!$result){
echo ' C li , khng th query database c' ;
}
else{
$array = mysql_fetch_assoc($result);
$rows = mysql_num_rows($result);
if($rows == 0){
echo 'Bn nhp sai password hoc username';
}
else{
session_start();
$_SESSION['user'] = $name;
$_SESSION['user_id'] = $array['user_id'];
$_SESSION['level'] = $array['level'];
if($array['level'] ==2){
// Nu ngi ang truy cp l admin th chuyn sang trang admin.php
header("Location: admin/admin.php");
exit();
}
else{
//Ngc li chuyn sang trang index.php
header('Location: index.php');
exit();
}
}
}
}
}
?>
<form action = 'login.php' method = 'post' >
<fieldset>
<legend> Log-in Form </legend>
<table>
<tr>
<td> Name : </td>
<td> <input type = 'text' name = 'txtname' size = '25' /></td>
</tr>
<tr>
<td> Password : </td>
<td> <input type = 'password' name = 'txtpass' size = '25' /> </td>
</tr>
<tr>
<td> </td>
<td> <input type = 'submit' name = 'ok' value = 'Log in' /> </td>
<!-t tn cho field submit d xc nhn xem ngi dng c nhn Submit
cha -->
</tr>
</table>
</fieldset>
</form>
Gii thch :
Chng ta quy nh : nu mun ang mua hng m ng nhp vo trang admin th hok
cho, chuyn ngi dng v gi hng, nu mun ng nhp th set gi hng la 0 ht b
sn phm ra khi gi hoc tin ti thanh ton ri mi cho ng nhp .
y dng form v cch x l form trn cng 1 trang nn chng ta phi c cch xc
nhn l nt Submit ca form c nhn cha ? Nu nhn ri th mnh x l form,
cn nu khng th hin th form cho ngi dng nhp .
gii quyt iu chng ta c :
PHP Code:
if(isset($_POST['ok'])){
//X l form
}
trn dng :
M:
<link href = '../styles.css' rel = 'stylesheet' type = 'text/css' />
PHP Code:
<?php
session_start();
if($_SESSION['level'] != 2){
header('Location: ../login.php');
exit();
}
?>
= trim(addslashes($_POST['category']));
Thay v c mi field trong form, chng ta check xem n c NULL hay khng , chng ta
cn dng 1 hm x l chuyn v b n vo 1 file trong folder includes :
check_data.php
PHP Code:
<?php
function check_data($vars){
foreach ($vars as $key => $value){
if($key != 'image'){
if ( !isset($key) || $value == '' ){
return false;
}
}
}
return true;
}
?>
chuyn vo database .
Quan trng l, nu ngi dng nhp title :
Macs : vy rt ph ti nguyn v s gy kh khan v sau , v th chng ta
phi b cc khong trng 2 bn chng, tc l dng hm trim()..
c/ Thm sch :
Tip theo, mnh s x l file thm sch : insert_book.php
PHP Code:
<?php
require_once('../includes/session.php');
require_once('../includes/check_data.php');
if(isset($_POST['ok'])){
$isbn = $author = $title = $price = $description = '';
if(!check_data($_POST)){
echo 'Bn cha in ht thng tin ca sch';
}
else{
require_once('../includes/connect.php');
$isbn
= trim($_POST['isbn']);
$author = trim(addslashes($_POST['author']));
$cate_id = $_POST['cate_id'];
$title
= trim(addslashes($_POST['title']));
$price
= $_POST['price'];
$description =addslashes($_POST['description']);
if($_FILES['image']['name']){
move_uploaded_file($_FILES['image']['tmp_name'],"images
/".$_FILES['image']['name']);
$image = addslashes($_FILES['image']['name']);
$sql = "insert into books(isbn,author,title,cate_id,ima
ge,price,description)
values('$isbn','$author','$title', '$cate_id', '$image'
,'$price','$description')";
}
else
$sql = "insert into books(isbn,author,title,cate_id,pri
ce,description)
values('$isbn','$author','$title', '$cate_id','$price',
'$description')";
$result = mysql_query($sql);
if($result){
header("location: ../index.php?cate_id=$cate_id");
exit();
}
else
echo ' Xy ra li , sch cha c thm vo ' ;
}
}
?>
<form action ='insert_book.php'
method = 'post' enctype = 'mult
ipart/form-data'>
<fieldset>
<legend> Thng tin sch : </legend>
<table>
<tr>
<td>Chuyn mc: </td>
<td>
<select name = 'cate_id'>
<?php
require_once('../includes/connect.php');
$sql = 'select * from categories';
$result = mysql_query($sql);
while($rows = mysql_fetch_assoc($result))
//Dng mysql_fetch_assoc s tit kim b nh hn mysql_fetch_array
echo "<option value = '$rows[cate_id]'>$rows[cate_n
ame] </option>";
//Ti sao hok phi l $result['cate_id'] m l $result[cate_id] <<< V
c lng vo " " ca dng ECHO
?>
</td>
</tr>
<tr>
<td>ISBN: </td>
<td><input type ='text' name = 'isbn' /> </td>
</tr>
<tr>
<td>Tc gi: </td>
<td><input type ='text' name = 'author' /> </td>
</tr>
<tr>
<td>Ta sch: </td>
<td><input type ='text' name = 'title' /> </td>
</tr>
<tr>
<td>Hnh i din: </td>
<td><input type = 'file' name = 'image' /> </td>
</tr>
<tr>
<td>Gi sch: </td>
<td><input type ='text' name = 'price' /> </td>
</tr>
<tr>
<td>M t: </td>
<td><textarea name = 'description' cols = '50' rows ='20'></tex
tarea></td>
</tr>
</fieldset>
<tr>
<td colspan = '2' align = 'center'><input type = 'submit' name
= 'ok' value = 'Send' /> </td>
</tr>
</form>
Vi mi dng duyt qua, gn mng bt tun t ca dng cho bin $rows, ri chuyn
con tr mng ln dng k tip
phn thm sch ny, chng ta cho php ngi dng upload file, nn khi khai bo form
phi c :
M:
enctype = 'multipart/form-data
d/ Hin cc chuyn mc :
Tip theo, mnh s x l file list chuyn mc : list_cates.php
PHP Code:
<link href = '../styles.css' rel = 'stylesheet' type ='text/css' />
<script>
function xacnhan(){
if(!window.confirm("Bn c thc s mun xa chuyn mc ny ?"))
{
return false;
}
}
</script>
<?php
require_once('../includes/session.php');
require_once('../includes/connect.php');
?>
<table border ='1' cellspacing ='0'>
<tr>
<th class
<th class
<th class
<th class
</tr>
=
=
=
=
'green_th'> S th t </th>
'green_th'>Tn chuyn mc </th>
'green_th'> S sch trong chuyn mc </td>
'green_th' colspan = '2'> Mt s quyn hn </th>
<?php
$sql = 'select * from categories ';
$result = mysql_query($sql);
$stt =0;
while($rows = mysql_fetch_assoc($result)){
$count_book_query = "select isbn from books where cate_
id =$rows[cate_id]";
$result_count = mysql_query($count_book_query);
$count = mysql_num_rows($result_count);
$stt++;
echo " <tr>
<td class = 'green_td' align = 'center'>$stt </td>
<td class = 'green_td' align = 'center'>$rows[cate_
name]</td>
<td class = 'green_td' align = 'center'>$count</td>
<td class = 'green_td' align = 'center'><a href = \
"edit_cate.php?cate_id=$rows[cate_id]\"> Edit </a> </td>
<td class = 'green_td' align = 'center'><a href = \
"delete_cate.php?cate_id=$rows[cate_id]\" onclick = 'return xacnhan();'
> Delete </a></td>
</tr>";
}
?>
</table>
<?php
echo "<a href = '../logout.php'> Log out | </a>";
echo "<a href = 'admin.php'> V trang qun tr </a>";
?>
S dng :
M:
<td class = 'green_td' align = 'center'><a href = \"delete_cate.php?
III/Layout:
a/ Trang ch
Tip theo, mnh s x l file layout sch : index.php . t file ny ngang cp vi folder
admin
PHP Code:
<link href = 'styles.css' rel = 'stylesheet' type = 'text/css' />
<?php
require_once('header.php');
require_once('includes/connect.php');
echo '<h1><font color = "red"> Cc chuyn mc : </font></h1> ';
$sql = 'select * from categories';
$result = mysql_query($sql);
echo '<ul>';
while($rows = mysql_fetch_assoc($result)){
echo "<li><a href = \"list_books.php?cate_id=$rows[cate_id]\" >
$rows[cate_name] </li>";
}
echo '</ul>';
session_start();
if(!isset($_SESSION['level'] ))
echo '<a href = "login.php"> ng nhp </a>';
else if($_SESSION['level'] == '2')
{
echo '<a href = "admin/admin.php"> n trang qun tr </a>';
echo '<a href = "logout.php"> Log Out</a>';
}
//require_once('footer.php');
?>
Ti trang ny, chng ta s list cc chuyn mc theo dng unordered list(<ul> </ul>) c
trong database, nhng khng phi sa, xa nh bn admin m l xem sch trong
chuyn mc .
lm c iu ny, chng ta ch cn thc hin 1 cu truy vn ly tt tn tt thng
tin v chuyn mc ri chuyn ha n thnh mng . Sau xut ra bng dng while . Ti
mi chuyn mc, t 1 link n file list_books.php?cate_id= <<<list_books.php c
nhim v lit k sch trong chuyn mc vi cate_id tng ng .
Ti y, nu ngi ang truy cp l admin th hin ch : V trang qun tr v log-out
Nu khng phi th hin ch : ng nhp
b/ Hin cc sch c trong chuyn mc :
Ti file list_books.php :
PHP Code:
<link href = 'styles.css' rel = 'stylesheet' type ='text/css' />
<?php
require_once('header.php');
require_once('includes/connect.php');
session_start();
$cate_id = $_GET['cate_id'];
$sql = "select isbn,image,title from books where cate_id = '$cate_i
d' ";
$result = mysql_query($sql);
echo '<table>';
while($rows = mysql_fetch_assoc($result)){
if($rows['image'] != NULL){
echo "<tr>
<td><img src = \"admin/images/$rows[image]\" widt
h = '100px' height = '150px' border = '1'/></td>
<td><a href = \"book_info.php?isbn=$rows[isbn]\" > $ro
ws[title] </li>";
}
else
echo "<tr>
<td><img src = # width = '100px' height = '150px'
/></td>
<td valign = 'center'><a href = \"book_info.php?isbn=$
rows[isbn]\" > $rows[title] </li>";
}
echo '</table>';
echo '<a href = "index.php"> n cc chuyn mc khc </a>';
if(!isset($_SESSION['level']) || $_SESSION['level'] != '2')
echo '<a href = "show_cart.php"> Xem gi hng ca bn </a>';
else
echo '<a href = "logout.php"> Log Out</a>';
//require_once('footer.php');
?>
Chng ta s lit k cc sch trong chuyn mc theo 1 bng, ct bn tri l hnh i din,
ct bn phi l ta sch , ta sch c gn link n file book_info.php?isbn. <<<file
book_info.php c nhim v lit k thng tin sch c isbn ch nh
V hnh nh l optional, v th chng ta phi xt 2 trng hp, nu hnh trn database l
NULL, th chng ta s khng show hnh ra ( src = # ) , ngc li, tr ng dn ti folder
images to, ly hnh upload show ra : admin/images/$rows[image]
c/ Hin th thng tin sch :
PHP Code:
<link href = 'styles.css' rel = 'stylesheet' type ='text/css' />
<script>
function xacnhan()
{
if(!window.confirm("Bn thc s mun xa sch ny? " )){
return false;
}
}
</script>
<?php
require_once('header.php');
require_once('includes/connect.php');
session_start();
$isbn = $_GET['isbn'];
$sql = "select * from books where isbn = '$isbn' ";
$result = mysql_query($sql);
$rows = mysql_fetch_assoc($result);
$isbn = htmlspecialchars($rows['isbn']);
$title = htmlspecialchars($rows['title']);
$author =htmlspecialchars($rows['author']);
$description = htmlspecialchars($rows['description']);
echo '<table>';
if($rows['image'] != NULL){
echo "<tr>
<td><img src = \"admin/images/$rows[image]\"
th = '100px' height = '150px'/></td>";
wid
}
else
echo "<tr>
<td><img src = # width = '100px' height = '150px'
/></td>";
echo "<td><ul>
<li>ISBN: $isbn</li>
<li>Title: $title</li>
<li>Author: $author</li>
<li>Price: $rows[price]</li>
phn ny, nu ngi ang truy cp l admin th xut ra : Sa thng tin sch, Xa sch
khi chuyn mc, v trang trc, log out .
PHP Code:
if(isset($_SESSION['level']) && $_SESSION['level'] ==2)
{
echo "<a href = \"admin/edit_book.php?isbn=$isbn\"> Sa thng tin s
ch| </a>";
echo "<a href = \"admin/delete_book.php?isbn=$isbn\" onclick =
\"return xacnhan();\"> Xa sch khi chuyn mc|</a>";
echo "<a href = \"list_books.php?cate_id=$rows[cate_id]\"> V trang
trc |</a>";
echo '<a href = "logout.php"> Log Out</a>';
}
}
}
foreach($_SESSION['cart'] as $isbn_i => $quantity_q){
$sql = "select price from books where isbn = '$isbn_i' ";
$result = mysql_query($sql);
$rows = mysql_fetch_assoc($result);
$price = $rows['price'];
$_SESSION['total_items'] += $quantity_q;
$_SESSION['total_prices'] += $quantity_q*$price;
}
echo "<h1><font color = 'red'> Gi hng ca bn </font></h1>";
echo "<form action = \"show_cart.php\" method = 'post'>";
echo '<table border = "1px" cellspacing = "0">';
echo '<th>Ta sch</th>';
echo '<th>Gi sch</th>';
echo '<th>S lng </th>';
echo '<th>Tng tin</th>';
foreach($_SESSION['cart'] as $isbn_i => $quantity_q){
$sql = "select * from books where isbn = '$isbn_i' ";
$result = mysql_query($sql);
$rows = mysql_fetch_assoc($result);
echo '<tr>';
echo "<td align = 'center'>$rows[title]</td>";
echo "<td align = 'center'>$rows[price]</td>";
echo "<td align = 'center'><input type = 'text' name = '$isbn_i
' value = '$quantity_q' size ='2' /></td>";
$total_prices = $rows['price']*$quantity_q ;
echo "<td align = 'center'>$total_prices</td>";
echo '</tr>';
}
echo '<tr>';
echo "<td align = 'center' colspan = '4'>
<input type ='hidden' name = 'save' />
<input type ='image' src = 'save.gif' /></td>";
echo '</form>';
echo '</table>';
if($isbn){
echo "<a href = \"list_books.php?cate_id=$book_ordered[cate_id]\">
Tip tc mua hng </a>";
}
else
echo '<a href = "index.php"> Tip tc mua hng </a>';
Sau chng ta tnh tng tin ca cun sch xut ra bng cch nhn gi sch vi tng
s lng sch :
PHP Code:
$total_prices = $rows['price']*$quantity_q ;
PHP Code:
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = array();
}
if(!isset($_SESSION['cart'][$isbn])){
$_SESSION['cart'][$isbn] = 1;
}
else
$_SESSION['cart'][$isbn]++;
Trc khi thc hin vic tnh ton tng sch v tng tin ( gi tr ca 2 SESSION trn),
chng ta cn x l nt save trc :
PHP Code:
if(isset($_POST['save'])){
//Nu ngi dng nhn nt save
foreach($_SESSION['cart'] as $isbn_i => $quantity_q){
//Lp vi tng cun sch trong gi
if($_POST[$isbn_i] ==0){
//Nu s lng sch ca 1 cun sch xc nh l 0, th b cun sch
ra khi gi hng
unset($_SESSION['cart'][$isbn_i]);
}
else
$_SESSION['cart'][$isbn_i] = $_POST[$isbn_i];
//Nu khc khng, cp nht s lng sch
}
}
$price = $rows['price'];
//Ly gi ca sch gn vo bin
$_SESSION['total_items'] += $quantity_q;
//Tng s sch th c tnh d dng bng cch cng dn tng s lng t
ng cun sch
$_SESSION['total_prices'] += $quantity_q*$price;
//Tng tin th cng dn tng tin mua mi loi sch .
}
$result = mysql_query($sql);
$rows = mysql_num_rows($result);
if($rows == 0){
if($_FILES['image']['name']){
move_uploaded_file($_FILES['image']['tmp_name']
,"images/".$_FILES['image']['name']);
$image = $_FILES['image']['name'];
$sql = "update books set isbn = '$isbn', author
= '$author', title ='$title', cate_id = '$cate_id', image ='$image', p
rice = '$price',
description = '$description' where isbn ='$old_isbn'";
}
else
$sql = "update books set isbn = '$isbn', author
= '$author', title ='$title', cate_id = '$cate_id', price = '$price',
description = '$description' where isbn ='$old_isbn
'";
$result = mysql_query($sql);
}
else{
echo 'Xy ra li .ISBN tn ti';
$result = false;
}
}
if($old_isbn == $isbn){
if($_FILES['image']['name']){
move_uploaded_file($_FILES['image']['tmp_name']
,"images/".$_FILES['image']['name']);
$image = $_FILES['image']['name'];
$sql = "update books set isbn = '$isbn', author
= '$author', title ='$title', cate_id = '$cate_id', image ='$image', p
rice = '$price',
description = '$description' where isbn ='$old_isbn'";
}
else
$sql = "update books set isbn = '$isbn', author
= '$author', title ='$title', cate_id = '$cate_id', price = '$price',
description = '$description' where isbn ='$old_isbn'";
$result = mysql_query($sql);
}
if($result){
header("location: ../list_books.php?cate_id=$cate_id");
exit();
}
else
echo ' Xy ra li , sch cha c thm vo ' ;
}
}
?>
Th khi c li hok thay i sch c, PHP s vn chy script edit_book.php m hok thc
hin vic chuyn trang => Lc ny hok cn isbn na m $_GET => form s y li v
hok c mng bt tun t d liu t database
Page 410 of 413
V vy chng ta thm :
PHP Code:
else if(isset($_POST['old_isbn'])){
$old_isbn = $_POST['old_isbn'];
$sql = "select * from books where isbn = '$old_isbn' ";
}
$result = mysql_query($sql);
}
Ri sau tm s dng ca kt qu tr v :
PHP Code:
$rows = mysql_num_rows($result);
Nu 0 dng, tc l khng c trng, chng ta thc hin cu truy vn thay i thng tin :
PHP Code:
$result = mysql_query($sql) . //tr v true
Code ny cn thiu phn check out, thanh ton, phn user th cha
kim tra tn ti username cha nh isbn trn , cc bn t x l nh,
coi nh bi tp v nh =]]] ^^
Cho mi ngi nh !