Sie sind auf Seite 1von 196

NGN NG LP TRNH PHP

1. Nhng im mnh ca PHP


-PHP thc hin vi tc rt nhanh v hiu qu .Mt Server bnh
thng c th p ng c hng triu truy cp ti trong mt ngy.
PHP h tr kt ni ti rt nhiu h CSDL khc nhau:
PostgreSQL,mSQL,Oracle,
dbm,
filePro
,Hyperware,
informix,InterBase, Sybase, ... Ngoi ra cn h tr kt ni vi ODBC
thng qua c th kt ni vi nhiu ngn ng khc m ODBC h
tr.
-PHP cung cp mt h thng th vin phong ph : Do PHP ngay t
u
c thit k nhm mc ch xy dng v pht trin cc ng
dng
trn
web nn PHP cung cp rt nhiu hm xy dng sn gip thc hin
cc
cng vic rt d dng : gi, nhn mail ,lm vic vi cc cookie, v
nhiu
th khc na .
-PHP l mt ngn ng rt d dng, d hc v n gin hn nhiu
so vi cc ngn ng khc nh Perl, Java. Nu bn bit ngn
ng C th mi vic s hon ton thun li .
-PHP c th s dng c trn nhiu h iu hnh, chng ta c th
vit
chng trn Unix, Lunix v cc phin bn ca Windows. V c th
em
m PHP ny chy trn cc h iu hnh khc m khng phi sa
i
li
m.
-PHP l ngn ng m ngun m.
I. Bin, hng s v kiu d liu trong PHP.
1. Kiu d liu .
PHP c ba kiu d liu c bn : interger, double v string. Ngoi ra
cn c cc kiu d liu khc (nhng khng phi cc kiu d liu
c bn) nh arrays (cc kiu d liu mng), objects (cc kiu d
liu i tng).
Interger l kiu chim 4 byte b nh ,gi tr ca n trong khong
-2 t ti + 2 t. Kiu Double l kiu s thc ,phm vi biu din (10-

10308). Kiu string dng cha cc gi tr bao gm cc k t v


con s .
308

V d : 2

// y l kiu interger

1.0

// y l kiu double

// y l kiu string
4

2 hours// y l mt kiu string khc


2. Hng s
Hng s l nhng gi tr khng i. Chng ta thng dng hng s
lu cc gi tr khng i trong sut chng trnh nh : nhit
(00C), cc gi tr thi gian ch s chuyn giao gia sng ,cha ,chiu
,ti ...
a. Khai bo hng s :
Ta dng hm define() khai bo hng
s : define(COMPANY, Phops
Bicycles); define(YELLOW,
#FFFF00);
define(VERSION, 4);
define(NL, <BR>\n);
Trong v d trn chng ta dng hm define() khai bo hng
s NL. Hng s ny l mt th ngt dng trong HTML.
Chng ta s s dng cc hng s trong PHP nh
sau :
echo (Employment at . COMPANY. NL);
Cch vit trn cng ging nh cc vit sau:
echo (Employment at Phops Bicycles<BR>\n);
Ch : hng s phi ngoi hai du v . Trng hp sau l khng
c hiu lc : echo (Employment at COMPANY NL);. Khi thc hin n
s cho kt qu l : Employment at COMPANY NL.
Hm defined() : hm ny dng kim tra xem mt hng s no
c khai bo cha.
V d : if ( defined (YELLOW)) {
echo (<BODY BGCOLOR=. YELLOW. >\n);
}

b. Cc hng s c nh ngha trong PHP (Built-in Constants):


h tr cho ngi lp trnh, PHP cung cp sn cc hng s nh :
cc bin mi trng, cc bin ca Web server Apache ... Ngi lp trnh c
th s dng hm phpinfo() xem cc gi tr ny.
<HTML>
<!phpinfo() -->
<BODY>
<?php phpinfo();?>
</BOCY>
</HTML>

+ Hng s nguyn : y l nhng gi tr c kiu integer. V d :


10
+ Hng s thc: y l nhng gi tr c kiu double. V d :
10.00
+ Hng k t : y l mt xu k t t trong du ngoc n
hoc
kp.
V d : Ngn ng lp trnh PHP.

3. Bin v gi tr logic.
+ Cng ging vi C/C++, PHP khng c khi nim TRUE v
FALSE. Cc gi tr TRUE c hiu l nhng gi tr bng 1 v gi tr
FALSE l nhng gi tr bng 0 hoc xu rng .
+ Khi s dng bin chng ta khng cn khai bo kiu .
V d : $a = 1; // $a l mt bin kiu integer.
$a = 1.2; // by gi $a l mt bin kiu double.
$a = A ; // by gi $a li l mt bin kiu string.
+ Nu nh thc hin php ton gia bin c kiu s v kiu
string, PHP s coi chui l mt dy s nh sau :
$str = 222B Baker Street;
Ta thy bin $str c gi tr kiu string, v nu cng s 3 vi gi tr ny
th :
$x = 3 + $str ;

// $x = 225

khi bin $x nhn c gi tr 255 v PHP cng 3 vi ba s


u. Nhng nu ta in gi tr ca bin $str th
echo ($str);

// print : 222B Baker Street

Ch rng cc php ton gia s v chui ch ng khi k t u ca


chui l s .
+ Ta cng c th lm thay i kiu gi tr ca mt bin bng cch p
kiu
$a = 11.2;

// bin $a c kiu double

$a = (int)

$a; // by gi $a c kiu integer ,gi tr l 11

$a = (double)

$a; // by gi $a li c kiu double, gi tr l 11.0

$b = (string)

$a ; // bin $b c kiu string ,gi tr l 11

Cng phi bit rng PHP t ng chuyn i kiu rt tt. Nu tht


s cn thit chng ta mi phi dng cch trn.

+ Cc hm lm vic vi bin
gettype() : hm ny tr li kiu ca mt bin no . Gi tr tr
v c th l : integer
double
string
array
object
class
unknown type
v d :
if

(gettype($user_input)

==

integer)
{
$age = $user_input;
}
settype() : hm ny p kiu cho mt bin no . Nu thnh
cng hm tr v gi tr 1 (true) ,ngc li l 0 (false).
v du :
$a = 7.5;
settype($a, integer);
if (settype($a, array)){
echo (Conversion succeeded. );
}else{
echo (Conversion error. );
}
isset() v unset() : Hm isset() kim tra mt bin c gn gi
tr hay cha, hm unset() s gii phng b nh cho mt bin no .
v d :

$id = 323bb;
if (isset($id)) {
echo (D liu c gn);
}else{
echo (D liu cha c gn);
}
unset($id);
if(!isset($id)) {
echo (D liu c gii phng);
}
empty() : Cng ging hm isset(), hm empty() s tr v gi tr 1
(true) nu mt bin l rng v ngc li 0 (false). i vi bin c kiu
s
gi tr bng 0 c coi l rng, bin kiu string c coi l rng nu
xu l
xu rng.
v d:
echo empty($new) ;

// true

$new = 1;
echo empty($new);

// false

$new = ;
echo empty($new);

// true

$new = 0;
echo empty($new);

// true

$new = So 323;
echo empty($new);

// false

unset($new);
echo empty($new);

// true

III. Cc ton t
+ Bng cc php ton s hc
Php ton ngha

V d Gii thch
Thc hin php cng gia 7 v 2 : 9

Php cng

7+2

Php tr

7-2

Php nhn 7 * 2

Thc hin php nhn gia 7 v 2 : 14

Php chia

7/2

Thc hin php chia gia 7 v 2 : 3.5

Chia d

7 % 2 Thc hin php chia d gia 7 v 2 : 1

Thc hin php tr gia 7 v 2 : 5

Ta c th vit cc php ton ngn gn nh bng sau :


Khi vit
$h += $i
$h -= $i
$h *= $i
$h /= $i
$h %= $i
+ Php gn :

Tng ng vi
$h = $h + $i
$h = $h - $i
$h = $h * $i
$h = $h / $i
$h = $h % $i

v d :
$x = 1;
$y = $x + 1;
$length = $area / $width;

10

+ Bng cc php ton quan h


Php ngha
ton
==
<
>
<=
>=
!=

So snh bng
So

snh

nh

Gii thich

$h ==
$i

Kim tra $h v $i c bng nhau


khng

$h < $i Kim tra $h c nh hn $i khng

hn
So

V d

snh

ln

$h > $i Kim tra $h c ln hn $i khng


$h <=
$i

hn

Nh hn hoc
<> bng

$h =>
$i

Ln hn hoc
bng

$h != $i
$h <>
$i

So snh khc
So snh khc

Kim tra $h c nh hn hoc bng $i


Kim tra $h c ln hn hoc bng $i
Kim tra $h c khc $i khng
Kim tra $h c khc $i khng

Cc php so snh thng dng kim tra iu kin trong cc cu


lnh iu khin m ta s hc bi sau .
+ Bng cc php ton logic
Php ton logic cng vi ton hng to thnh biu thc logic. Biu
thc logic c th c gi tr l 1 (true) hoc 0 (false) .

Ton hng a

Ton hng b

a && b

a || b

!a !b

+ Cc php ton vi bin kiu string .

11

Ta s dng du . ghp hai bin kiu string vi


nhau

.
v d : $first = Phineas;
$last = Phop;
$full = $first. . $last;

// $full = Phineas Phop ;

echo ($full);
Ta c th ghp hai xu nh sau:
echo ($last. s Bicycles); //print : Phops Bicycles
c th chn mt bin vo trong hng c kiu string th tn
bin phi trong du ng m ngoc nhn.
echo (${last}s Bicycles);
+ Cc php ton thao tc mc bit.
Cc php ton thao tc mc bit tc ng ln tng bit ca ton hng .
K hiu

ngha

&

AND bit

OR bit

XOR bit

Bng cc php ton nh sau :


&

Kt qu

Kt qu

Kt qu

1&1

1|1

1^1

1&0

1|0

1^0

0&1

0|1

0^1

0&0

0|0

0^0

PHP cng h tr cc php dch phi v dch tri >> :


dch phi
<< : dch tri
Gi s $a l mt bin nguyn th php ton : $a >> n lm cho
cc bit trong $a b dch phi i n v tr. Tng t ta c php dch
tri .
12

v d : 11 >> 2 = 2 ;
v :
11 (1011)
>> 2
2 (0010)
+ Cc php ton tng gim :
- Php tng : php tng (ton t tng) tng gi tr ca ton
hng ln mt n v.
$a ++ : $a c s dng ri mi
tng
++ $a : $a tng ri mi c s
dng
- Php gim : tng t nh php tng, khc l gi tr b gim
i
mt
n v.
$a -- : $a c s dng ri mi
gim
-- $a : $a gim ri mi c s
dng
v d :
$a = 10;

// $a bng 10

$b = $a++ ; // $a bng 11 nhng $b bng 10


$a = 10;

// $a bng 10

$b = -- $a ; // $a bng 9 v $b bng 9
+ Php ton iu kin. ? :
Php ton iu kin cng vi ton hng to nn biu thc iu
kin. Ta k hiu e1 ,e2, e3 l ba ton hng.
Biu thc c dng : e1 ? e2 : e3
Nu e1 != 0 th gi tr ca biu thc iu kin l
e2
Nu e1 == 0 th gi tr ca biu thc iu kin l

e3
v d : tm max
max = $a>$b ? a : b ;

13

+ Ton t sizeof (i tng) :


Php ton sizeof cho bit kch thc (tnh bng byte ) nh m i
tng chim trong b nh. i tng y c kiu l integer,
double,
string.
v d : $a = 10;
echo sizeof($a); //s in ra mn hnh l : 4
IV. Cc cu lnh iu khin
1. Lnh if_else : y l lnh r nhnh c iu kin .
a. Dng 1 :
if ( biu thc ) cu lnh;
Cu lnh y tng ng vi mt khi lnh. Mt khi lnh
c t trong du ngoc kp.
ngha :
+ Nu biu thc khc khng ,th cu lnh c thc hin.
+ Nu biu thc bng khng, th cu lnh khng c thc hin
b. Dng 2 :
if ( biu thc )
cu lnh 1;
else
cu lnh 2;
ngha :
+ Nu biu thc khc khng ,th cu lnh 1 c thc
hin.
+ Nu biu thc bng khng, th cu lnh 2 c thc
hin
Ch :
* Cu lnh 1 dng 2 l lnh if_else

14

+ Nu lng else bng lng If th else thuc v If gn


nht theo tng cp t trong ra ngoi.
V d :
$a = 10; $b = 10;
$c = 3; $d = 3;
$e = 12; $f = 8;
if($a == $b)
if($c == $d)
if($e == $f)
$max = $e;
else
$max = $f;
else
$max = $d;
else
$max = $b
echo $max ;
//printf max = 8
+ Nu lng else t hn lng If th else thuc v If ngn
nht theo tng cp t trong ra ngoi.
V d :
<?php
if ($a == $b)
if ($c == $d)
$max = 0
else
$max = $d;
?>
Tng ng vi :
<?php
if ($a == $b)
{
}
else
?>

if ( $c == $d)
$max = 0;
$max = $b;

* Cu lnh 2 ca dng 2 l elseif :


15

Bt ngun t :
if ( biu_thc1 )
cu_lnh 1;
else
if ( biu_thc 2 )
cu_lnh 2;
else
if ( biu_thc 3 )
cu_lnh 3;
else
if ( biu_thc i )
cu_lnh i;

C th vit li nh sau:
if ( biu_thc1 )
cu_lnh 1;
elseif (biu_thc 2)
cu_lnh 2;
elseif (biu_thc 3)
cu_lnh 3;
elseif (biu_thc i)
cu_lnh i;
else
cu_lnh n;

else
cu_lnh n;
Cu lnh elseif to ra lnh r nhnh c iu kin trong
thc hin 1 trong n cch khc nhau.
- Nu biu_thc i khc khng (i = 1,..n-1) th thc hin cu
lnh i .
- Nu biu_thc i bng khng (i = 1, ..n-1) th cu lnh th
n c thc hin.
2. Cu lnh switch :
switch (biu_thc n)
{
case n1:
cu lnh 1;
break;
case n2:
cu lnh 2;
break;

case nn:
cu lnh nn;
[default: cu lnh]

16

Cu lnh switch l cu lnh r nhnh c iu kin trong


thc hin mt trong n ci r nhnh.
+Nu biu_thc n = ni (i = 1, .. n) th cu lnh sau case ni
c thc hin cho n khi gp lnh break hoc du ngoc }
+Nu biu_thc n != mi ni (i = 1, .. n) m c nhnh Default
th cc cu lnh sau Default c thc hin.
V d :
<?php
$val = 6;
$a = 5;
$b = 6;
$d = 7;
switch ($val)
{
case $a :
echo (five);
break;
case $b :
echo (six);
break;
case $c :
echo (seven);
break;
default :
echo ($val);
}
?>
3. Cu lnh FOR:
Dng lnh :

for (biu_thc 1; biu_thc 2; biu_thc 3)


cu lnh ;

Lnh for l lnh to chu trnh c iu


kin. Bc 1 : tnh biu_thc 1
Bc 2 : tnh biu_thc 2 :
Nu biu_thc 2 khc 0 th thc hin cu lnh v sang bc 3.

17

Nu biu_thc 2 bng 0 th kt thc vng


for Bc 3 : tnh biu_thc 3 v quay li bc 2.
+ biu_thc 1, biu_thc 2, biu_thc 3 l cc thnh phn. Mi
thnh phn c th gm nhiu biu thc. Khi mi biu thc c
vit cch nhau mt du phy (,).
+Cc biu thc c tnh ln lt t tri qua phi
+Biu thc trong biu_thc 2 quyt nh thc hin thn ca for.
V d :

<?php
for($i = 0; $j = 4,$i < $j; $i++,$j--)
{
echo (i =. $i. ,j = . $j. <br>);
}
?>

+C th vng mt bt k thnh phn no. Nu vng mt biu_thc


2
th cu lnh lun c thc hin. Mc d vng mt vn phi c du
chm
phy (;)
V d :
<?php
for ( ; ; ) {
if (my_function() == stop)
break;
}
?>
+Nu vng biu_thc 1 v biu_thc 3 th :
for ( ; biu_thc 2 ; ) cau_lenh ;
tng ng vi :
while (biu_thc 2) cau_lenh ;
4. Cu lnh WHILE
while (biu_thc)
cu lnh ;

18

Lnh while l mt lnh to chu trnh c iu kin. iu kin thc


hin c kim tra u chu trnh.
Bc 1 : Tnh biu thc
Nu biu thc khc khng, sang bc 2
Nu biu thc bng khng, kt thc vng
while Bc 2 : Thc hin cu lnh.
Quay li bc 1.
Ch :
+ Biu thc c th bao gm nhiu biu thc. Khi cc biu thc
c vit cch nhau mt du phy ,v c tnh ln lt t tri
qua phi. Biu thc cui cng quyt nh thc hin cu lnh.
+ Khng c php vng mt biu
thc + to chu trnh v tn th
while(1)
{
if (biu_thc) break;
}
V d :
$i = 11;
while (--$i)
{

if (my_function($i) == error) {
break;
}
++ $number;

19

5. Lnh DO ... WHILE


Dng lnh :
do {
cu lnh;
}while (biu_thc);
Lnh do ... while l lnh to chu trnh c iu kin, trong iu
kin thc hin chu trnh c kim tra cui chu trnh.
Hot ng :
Bc 1 : Thc hin cu lnh
Bc 2 : Tnh biu thc biu_thc
+Nu biu thc biu_thc khc khng th quay li bc 1
+Nu biu thc biu_thc bng khng th kt thc do ...
while.
V d :
<?php
echo

(<SELECT

name=num>\n); $i = 0;
$total = 10;
do {
echo

(\t

<OPTION

value=$i>$i</OPTION>\n); }while(++ $i < $total);


echo (</SELECT>\n);
?>
6. Lnh break
L lnh r nhnh khng iu kin v thng dng ra khi thn
ca switch, while, do ... while, for .

20

Lnh break ch cho php thot khi thn cc lnh bn trong nht cha
n.
7. Lnh continue
L lnh r nhnh khng iu kin .Lnh thng dng bt u
li mt chu trnh mi trong cc lnh for, while, do ... while m khng
cn thc hin ht ton b thn ca ca lnh to chu trnh.
8. Khai bo tin x l include v require .
s dng cc on m bn ngoi, chng ta c th s dng khai
bo tin x l include v require. Cho php chng ta xy dng cc
hm cc hng s, v bt k on m no sau c th chn vo cc
on script.
Require khc include l, n c th lm thay i ni dung ca trang
hin ti khi bin dch, cc trang ny dng khai bo cc bin,
cc hng s hay cc on m n gin khng c vng lp. Khi
include cho php thc hin cc cu lnh phc tp - c cu lnh to
chu trnh. N ch s dng cc hm nh nhng hm ngoi ca
chng trnh.
V. Hm trong PHP
1. Quy tc xy dng hm
function tn_hm (danh sch i s hnh thc)
{ Thn hm .
}
+ nh ngha hm khng nht thit phi nm ngoi thn mi
hm, trong hm c th c hm khc. Nhng vic s dng mt hm
khng khc nhau gia xy dng hm trong thn mt hm v ngoi
mi hm .
+ Tn hm tu t v khc tn hm chun.
+ Hm c th c gi tr tr v hoc khng.
+ Cc cu lnh c quyn gi bt k hm no c khai bo
v c nh ngha.

21

+ Return : - Tr mt gi tr v cho ni gi
hm
- L ni bo kt thc hm
2. Gi hm .
+ Hm phi c xy dng (khai bo) trc khi gi .
+ Khi gi hm, nu c gi tr tr v thng c t trong biu thc .
3. Bin ton c v bin cc b.
Thng thng PHP coi cc bin c s dng trong thn ca
hm l bin cc b. Ngha l bin trong thn hm khng lm thay i
gi tr ca bin ngoi hm . Mun hm lm thay i gi tr ca
bin ngoi ta cn khai bo global trc bin trong thn hm .
V d :
$position = m;
function change_pos()
{
$position = s;
}
change_pos();
echo ($position);

//Prints m

Ta thy bin $position gi tr khng i sau khi gi hm change_pos().


$position = m;
function change_pos()
{

global $position;
$position = s;

}
change_pos();
echo ($position);

//Prints s
22

Ta c th vit nh trn hoc ta c th vit :


$position = m;
function change_pos()
{

GOLOBALS[$position] = s;

}
change_pos();
echo ($position);

//Prints s

VI. Bin mng trong PHP


1. Mng mt chiu
Mng l mt bin bao gm nhiu phn t c cng tn nhng
khc nhau v ch s (cc ch s ny tng dn t 0 n n). Vi ngn ng
lp trnh C, cc phn t ca mng c cng kiu d liu ,nhng vi PHP
th mm do hn. Cc phn t ca mng khng nht thit phi cng
kiu.
a. Khai bo mng mt chiu.
Ta c th khai bo mng bng cch gn tn mng vi du ng
m ngoc vung khng c ch s. Chng ta hy xt v d sau :
$countries[] = cr;
$countries[] = de;
$countries[] = us;
V d trn to ra mt mng gm ba phn t c ch s l 0, 1 v
2. Vic cng tng t nh ta gn :
$countries[0] = cr;
$countries[1] = de;
$countries[2] = us;
Ngoi ra cc ch s ca mng khng nht thit phi tng dn m c
th c khai bo nh sau :
$countries[50] = cr;
23

$countries[20] = de;
$countries[10] = us;
echo ($countries[20]); // prints de
Khi thm mt phn t mi vo mng chng ta c th
vit $countries[] = uk; // ch s s l 51
Mt phn t mi c thm vo vi ch s l ch s ln nht ca
mng
cng thm mt. Ngoi ra cng c th khai bo mng mt chiu bng
cu
lnh array
$countries = array (cr, de,
us)
echo

;
($countries[2]);

//prints

us
ch s khng bt u t khng ta c th khai bo li nh
sau $countries = array (1 => cr, de, us);
echo ($countries[2]); //prints de
Ton t => c th c s dng trc bt k mt phn t no
trong
mng
$countries = array (cr, 7 => de, us);
v khi phn t c gi tr cr c ch s l 0 cn phn t c gi tr
de, us ln lt l 7 v 8. Khc vi ngn ng lp trnh C, ch s ca
mng mt chiu khng ch l cc s nguyn m cn l xu k t. Ta c
th
khai
bo nh sau :
$countries[ca] = Canada;
$countries[cr] = Costa Rica;
$countries[de] = Germany;
$countries[uk]
Kingdom;

United

$countries[us]

United States;

echo ($countries[ca]);

// print Canada

Nu dng array th s l :
$countries = (ca => Canada,

24

cr

=>

Costa

Rica,
de

=>

Germany,
uk

=>

Kingdom,

United
us

United States);

=>

25

b. Lm vic vi cc phn t ca mng


C th s dng vng lp for xt tng phn t ca
mng. $countries = array (cr, de, us);
$num_elements = count($countries);
for ($i = 0 ; $i < $num_elements ; $i +
+) {
echo ($countries[$i] <BR>\n);
}
V d trn s ng khi ch s ca cc phn t tng dn u. Nu ch
s
cc phn t khng theo mt th t no c ta c th s dng hm list() v
each().
reset ($countries);
while (list ($key, $value ) = each
($countries)) {
echo (Ch s $key, gi tr $value);
}
di chuyn con tr ti phn t tip theo hoc trc ta cng c
th dng hm next() - hm next() tr v l 1 (true) nu phn t
tip theo khng phi l phn t cui cng, ngc li l 0 (false)
v prev() - hm prev() cho gi tr tr v l 1 (true) nu phn t
tip theo khng phi l phn t u tin, ngc li l 0 (false).
Hm key () s cho bit ch s v hm current() s cho bit gi tr
ca phn t .
$arr = array (3, 4, 5, 6, 7);
do {
$k = key ($arr);
$val = current ($arr);
echo (Phn t $k = $val);
}while
2. Mng hai chiu

Chng ta c th khai bo mng hai chiu nh sau :

26

$countries = array (Europs => array (de, uk),


North America => array (ca, cr, us));
echo ($countries[Europs][1]);

// print uk

echo ($countries[North America][2]); // print us


Ta c cu trc ca mng trn nh sau :
$countries[Europs]

$countries[North America]

[0]

[1]

[0]

[1]

[2]

de

uk

ca

cr

us

Cng ging nh mng mt chiu ta s dng vng lp nh for,


while, do ... while duyt qua cc phn t ca mng.
V d :
$countries = array (Europs => array (de, uk),
North America => array (ca, cr, us));
while (list ($key1) = each
($countries)) {
echo ($key1 : <BR>\n);
while (list ($key2, $val) =
each($countries[$key1])) {
echo ( - $val <BR>\n)
}
}
Khi chy chng trnh s in ra mn hnh l
: Europ :
- de
- uk
North America :
- ca
- cr
- us

27

3. Cc hm sp xp mng .
PHP cung cp cho chng ta cc hm sp xp mng. Vi mi loi
mng s c mt hm tng ng. Vi mng c ch s l kiu nguyn
chng ta c hm sort() sp xp tng dn cc phn t ca mng, hm
rsort() s sp xp cc phn t ca mng gim dn .
$countries = array (us, uk, ca, cr,
de); sort ($countries);
while (list ($key, $val) = each ($countries)) {
echo

(Element

$key

equals

$val

<BR>\n);
}
Khi chy chng trnh s l :
Element 0 equals ca
Element 1 equals cr
Element 2 equals de
Element 3 equals uk
Element 4 equals us
Vi mng ch s c kiu string th dng hm asort (), arsort ()
sp
xp mng theo chiu tng dn v gim dn. Nu bn dng cc hm
sort() v
rsort() th cc ch s c kiu string s chuyn thnh cc ch s c kiu
nguyn.
$countries = array(us => United States,
uk => United Kingdom,
ca => Canada,
cr => Costa Rica,
de => Germany);
asort ($countries);
while (list($key, $val) = each($countries))
{

echo Chi so $key bang $val


<BR>\n;
28

}
Kt qu khi chy chng trnh
: Chi so ca bang Canada
Chi so cr bang Costa Rica
Chi so de bang Germany
Chi so uk bang United Kingdom
Chi so us bang United States
Nhng nu thay dng asort ($countries); bng sort ($countries);
kt qu s l
Chi so 0 bang Canada
Chi so 1 bang Costa Rica
Chi so 2 bang Germany
Chi so 3 bang United Kingdom
Chi so 4 bang United States
sp xp mng tng dn hay gim dn theo ch s chng ta c
hm ksort() - tng dn v krsort() - gim dn .
$countries = array(e => United States,
d => United Kingdom,
c => Canada,
b => Costa Rica,
a => Germany);
ksort ($countries);
while (list($key, $val) = each($countries))
{
echo Chi so $key bang $val
<BR>\n;
}
Kt qu :
Chi so a bang Germany

29

Chi so b bang Costa Rica


Chi so c bang Canada
Chi so d bang United Kingdom
Chi so e bang United States
VII. Lp trnh hng i tng (OOP)
1. nh ngha lp .
Chng ta c th nh ngha lp bng ton t class, v trong mi
mt lp chng ta s xy dng cc phng thc v thuc tnh cho lp
.
Gi s mun nh ngha lp Sesssion chng ta lm nh
sau

<?php
class Session
{
// nh ngha cc thuc tnh v phng
thc // Xy dng cc phng thc cho lp
}

// Kt thc mt lp

?>
nh ngha thuc tnh cho lp chng ta t t kho var trc
thuc tnh .
<?
class Session
{
var $sqlhost =
localhost;
var $sqluser = root;
var $sqlpass = password;
var $sqldb = session;

30

var $linkid;
var $seshid;
var $sessdata;
var $userid;
var $error_no;
var $err;
// nh ngha cc phng thc y
}

//Kt thc nh ngha lp

?>
Tip theo chng ta s nh ngha cc phng thc cho lp trn.
Phng thc cn xy dng u tin l Session() sau n cc
phng
thc
khc.
<?
// nh ngha lp Session
class Session
{
// nh ngha cc thuc tnh
// nh ngha cc phng thc
function

Session($localSeshID,

$localUserID=0)
{
$this->seshid = $localSeshID;
$this->userid = $localUserID;
// Kt ni ti MySQL
$this->linkid=mysql_connect($this->sqlhost, $this->sqluser,
$this>sqlpass);

31

if (!$this->linkid)
{
$this>err=mysql_error();
$this->error_no=102;
}
}
// nh ngha cc phng thc khc
}
?>
2. S dng lp c nh ngha.
khai bo mt i tng c kiu thuc lp xy dng ta
dng ton t new nh sau :
<?php
require (classes/sessions.php); //include class
$mysesh = new Session($seshid);
if ($mysesh->error_no)
{
//Thng bo c li
}
$user = $mysesh->sessdata[userid];
?>
<HTML>
<HEAD>
<TITLE>Welcome to my website, <? echo $user ?
></TITLE> </HEAD>
<BODY>
<a href=nextpage.php?seshid=<? print $user ?>>Next Page </a>
32

<FORM ACTION=nextpage.php METHOD=POST>


<input type=hidden name=seshid value=<? print
$seshid ?>> </FORM>
</BODY>
</HTML>
VIII. Tm hiu thm v HTML
Phn mt chng ta tm hiu s lc v ngn ng HTML.
Trong mc ny chng ta s trnh by thm v n vi trng tm l
FORM ca
HTML. L do l v khi mun giao tip gia HTML v PHP script th
khng th khng bit n FORM. FORM l cng c ph bin nht
chuyn d liu t HTML n PHP script (client ln server).
Thng thng, khi vit mt script, ngi ta thit k mt FORM sao
cho n cung cp y nhng thng tin m script cn x l.
1. Cu trc ca mt FORM
Mt FORM c m u bng th <FORM ... > v kt thc bng
th </FORM>.
Trong FORM c :
- Thuc tnh : FORM thng c ba thuc tnh, ba thuc tnh ny
nm trong th FORM m u ca mt FORM : action, method, enctype .
- Cc th c dng trong FORM : input, select, textarea, hn,
p, hr, dir, dl, menu, ol, ul, address, blockquote, [isindex]. pre .
- FORM c ba thnh phn chnh : textarea, select, input .
- FORM c th c dng trong cc th : blockquote,body,dd, li.
2. Cc thuc tnh
Khi to mt FORM ,cng vic u tin l xc nh thuc tnh ca
n.
- Thuc tnh action : Action=URL ch n script m FORM s
dng. Ngoi ra n cng c th l mailto url, khi ni dung ca FORM
c mail n a ch trong url .

33

- Thuc tnh method : Method c th c gn bng GET hoc


POST ,n ch ra phng thc Post hay Get s c s dng trong
FORM, gi tr ngm nh l Get.
- Thuc tnh enctype : Enctype=Mime_type :ch ra loi d
liu s gi i. Gi tr ngm nh l application/x-www-formurlencode.
Trong mt trang chng ta c th s dng nhiu FORM nhng
khng c lng chng vo nhau.
2. Cc thnh phn c bn ca FORM.
Mt FORM ,thng thng c ba thnh phn
chnh : +Textarea
+Select
+Input
a - Textarea
c bt u bng th <Texterea> v kt thc bng th
</Texterea>. Bn trong cha cc k t, th ny c dng lng vo
trong FORM.
Cc thuc tnh ca Texterea .
- Name : nh ngha tn ca thnh phn, thuc tnh ny lun lun phi
c.
- Rows : Cho bit s hng ca hp vn bn.
- Cols : Cho bit s ct ca vn bn.
Wrap : Ch ra cch x l word_wraping (cn chiu di ca dng
vn
bn theo kch thc ca hp vn bn) trong hp thoi. Nu
wrap=off, chc
nng word_wraping b cm. Nu wrap=vitual, chc nng ny c
bt ln,
khi g vn bn vo, ta thy con tr t ng xung hng mi khi n chy
n
bin ca hp vn bn, k t newline (OA hex) t ng c thm vo
nhng
khng c gi i cng FORM. Nu wrap=physical, chc nng ny
cng
c bt v hot ng nh trn nhng k t newline c gi i

cng vi
FORM.

34

Vn bn nm gia hai th <Texterea> v </Texterea> s c th


hin nh on vn bn ngm nh trong vng d liu.
V d:
<Texterea name=van_ban rows=4 cols=40>
</ Texterea >
b. Select
c bt u bng th <Select> v kt thc bng th </ Select >,
cp th ny c th lng trong FORM hay bt k thnh phn no ca
FORM ngoi tr Texterea v Select .
Select c cc thuc tnh sau :
- Name : Tn ca thnh phn.
- Size : Cho bit s thnh phn s hin th, gi tr ngm nh l 1,
do danh sch la chn thng c th hin di dng pop-up
menu. Thuc tnh ny c th khng c.
- Multiple : Nu thuc tnh ny c thit lp, nhiu la chn s
c chn cng mt lc, ngc li ch c chn mt item.
Khi s dng Select, chng ta c th dng thm Option
<Option>. .. . </Option>
Bn trong cha cc k t, c th c s dng lng vo
Select . Cc thuc tnh Option :
- Disable : nh mt la chn b cm. Khi hin th, chn la ny s
b che m.
- Selected : nh du chn la ny c chn, nu thuc tnh
Multiple c bt trong Select, bn c th nh du Selected nhiu
chn la cng lc. N dng nh du cc la chn ngm nh.
- Value : Ch ra gi tr c gn cho la chn, nu khng c th
ni dung ca th mc option s c gi i thay cho value.
c. Input
35

M u bng th < Input >, th ny c th dng trong bt c


thnh phn no khc ca FORM ngoi tr Texterea v Select.
Cc thuc tnh :
- Align : C th l mt trong ba gi tr top, middle, bottom dng
cn l nh vi cc vn bn xung quanh, thuc tnh ny ch c
ngha vi Type=image .
- Name : gn tn bin cho d liu ca thnh phn ny. Gi tr
ca thuc tnh do user la chn .
- Type : nh ra mt trong nhng gi tr sau checkbox, hidden,
image, password, radio, reset, submit, text, file, bottom .
- Checked : ch ra mt nt radio, hay mt checkbox c c chn
hay
khng.
- Maxlength : ch ra chiu di ti a m hp thoi vn bn c th
cha,
thuc tnh ny ch c ngha vi input c type=text hay
type=password .
- Size : ch ra kch thc thc s ca hp thoi vn bn.
IX. Tm lc
Nh vy, chng ta kho st hu ht cc chc nng c bn ca
PHP, t cc kiu d liu, khai bo bin,
hng, mng cho ti
cch thc hin chng trnh dng My khch/My ch
(Client/Server), v nhng cc on m PHP vo cc trang HTML
.v.v.
Nh trn chng ta trnh by, c s d liu cho trang Web l
thnh
phn khng th thiu, n ng vai tr quyt nh cho chng trnh. V
l
do
, phn tip theo chng ta s kho st ngn ng SQL v cc hm API
ca
PHP thc hin cc lnh truy vn trn h qun tr c s d liu
MySQL.
X. Cc hm API trong PHP
1. Gii thiu v MySQL .

PHP h tr mt s lng ln cc hm lm vic vi c s d


liu
nh
Oracle, Sybase, PostgreSQL, MySQL. .. Thng qua chun ODBC (Open
Database Connectivity), bng cch s dng cc hm API (Application
36

Programming Interface) m PHP c th lm vic c vi nhiu h qun


tr
c s d liu nh vy. Nu h qun tr c s d liu khng h tr
ODBC ,v
hn na ODBC c c im ch h tr dng chun th PHP c th lm
vic
vi ODBC tng trn. Nu khng mun s dng ODBC ta c th s dng
cc hm API .
Trong phn ny chng ta ch s dng cc hm API lm vic vi
h qun tr c s d liu MySQL .
2. Cc hm c bn lm vic vi c s d liu MySQL.
a) Cc hm kt ni n MySQL Server
PHP cung cp hai hm kt ni vi c s d liu MySQL
: mysql_connect v mysql_pconnect .
+ mysql_connect () : hm ny s to ra mt lin kt ti my
ch MySQL .
C php :
int mysql_connect (string [hostname [:port] [:/path_to_socket]],
string [username], string [password]);
Trong :
- hostname : Tn my ch c s d liu, ni trang web s cha
c s d liu. Gi tr ngm nh l localhost
- :port : a ch cng, ni b my c s d liu lng nghe yu cu.
Gi tr ngm nh l :3306 .
- :/path_to_socket : Cng ging nh :port nhng ch cho h iu
hnh UNIX. Gi tr ngm nh l :/tmp/mysql.sock .
- username : Tn ca ngi s dng c php kt ni vo b
my c s d liu.
- password : Mt khu ca ngi s dng kt ni vo b my c
s d liu.
Hm ny tr v m s nhn dng nu kt ni thnh cng, gi tr 0
(false) nu vic kt ni c li. M s nhn dng ny s c s dng
cho tt c cc yu cu ti b my c s d liu sau ny.

37

S kt ni ny s ng li khi gi hm mysql_close() hoc kt


thc on PHP script.
+ mysql_pconnect() : Hm ny to ra mt lin kt bn vng vi
my ch MySQL.
C php :
int mysql_pconnect (string [hostname [:port] [:/path_to_socket]],
string [username], string [password]);
Tham s v gi tr tr v ca hm ny cng ging hm
mysql_connect(). S khc bit gia hai hm ny l lin kt ti my ch
MySQL khng b ng li k c khi kt thc kch bn (script) PHP hay
gi hm mysql_close(). Mc ch ca hm ny l lun lun duy tr lin
kt ti my ch MySQL do lun c s yu cu ti my ch, trnh cho
my ch phi tm kim m s nhn dng mi t gim thi gian
truy cp .
Ch : hm ny ch thc hin c khi PHP c nh cu hnh
nh l mt module ca Web server .
+ mysql_close() : Hm ny hu b s kt ni ti my ch MySQL
. C php :
int mysql_close(int [link_identifier]);
Tham s link_identifier l m s nhn dng to ra bi hm
mysql_connect(). Hm tr v l True nu thnh cng, ngc li l False .
b) Cc hm thao tc trn CSDL
+ mysql_create_db() : Hm to c s d liu
C php :
int

mysql_create_db(string

name,

int

[link_identifier]) ; Trong :
- string name : Tn ca c s d liu cn to.
- int link_identifier : M s nhn dng c cp bi
hm mysql_connect() .
Chng ta hon ton c th gi cu lnh SQL to c s d liu
thng qua hm mysql_query() .

38

+ mysql_drop_db() : Hm xo c s d liu
C php :
int

mysql_drop_db(string

name,

int

[link_identifier]); Trong :
- string name : Tn ca c s d liu cn xo .
- int link_identifier : M s nhn dng c cp bi
hm mysql_connect() .
Chng ta hon ton c th gi cu lnh SQL xo c s d liu
thng qua hm mysql_query().
+ mysql_select_db() : Hm cho c s d liu hot ng
. C php :
int

mysql_select_db(string

database_name,

int

[link_identifier]); Trong :
- database_name : Tn ca c s d liu m sau ny cc hm
API khc ca PHP s thc hin trn .
- int link_identifier : M nhn dng c cp bi hm
mysql_connect().
Cu lnh ny s gn tn c s d liu vi m nhn dng, sau ny khi
lm vic vi link_identifier s bao gm c c s d liu c chn .
c) Cc hm thao tc trn d liu
+ mysql_query() : Hm gi cu lnh SQL ti my ch MySQL
. C php :
int

mysql_query(string

query,

[int

link_identifier]) ; Trong :
- string query : Cu lnh SQL cn gi ti my ch MySQL .
- int link_identifier : M s nhn dng, n phi c thc hin
trong hm mysql_select_db() trc .
+ mysql_db_query() : Hm gi cu lnh SQL ti my ch MySQL
. C php :

39

int mysql_db_query(string database, string query,


int [link_identifier]);
Trong :
- string database : Tn c s d liu cu lnh SQL s thc hin trn
. - string query : Cu lnh SQL cn thc hin .
- link_identifier : M s nhn dng c cp bi hm
mysql_connect()
Hm ny ch r cu lnh c thc hin trn c s d liu no nn
trc khng cn thc hin hm mysql_select_db();
+mysql_insert_id() :
Hm ly gi tr c sinh ra t cu truy vn INSERT trc
C php :
int
mysql_insert_id([link_identifier]) ;
trong :
int link_identifier : M s nhn dng c cp bi
hm mysql_connect() .
Hm ny tr v gi tr id c sinh ra trong ct
AUTO_INCREMENT bi cu truy vn trc . iu ny ch c tc dng
trn link_identifier c ch ra trong hm, nu gi hm trn m khng
ch nh tham s link_identifier th lin kt c m cui cng s c
ch nh.
Hm mysql_insert_id() tr v gi tr 0 nu cu truy vn trc khng
sinh ra mt gi tr AUTO_INCREMENT. Nu ta mun gi li gi tr cho
ln sau, th phi gi hm ny ngay sau cu truy vn sinh ra gi tr .
+ mysql_fetch_row() :
Hm tr v mt mng l gi tr ca mt bng ghi hin ti vi ch
s l s th t ca cc trng (ch s bt u t 0). Sau hm s tr
ti bng ghi tip theo cho ti khi gp bng ghi cui cng hm tr v gi
tr false. truy xut ti cc gi tr ca ct ta vit : tn_mng[s th t]
C php :
array mysql_fetch_row( int result_identifier);

40

Trong : result_identifier l m s tr v ca hm
mysql_query() hoc mysql_db_query() .
V d :
<?php
$mysql = select id, name from ds_thanhvien; // cau lenh
SQL $link = mysql_connect($host, $user, $password); //lay
ma
mysql_select_db($database_name, $link);
$result = mysql_query($mysql ,$link);
while ($row =
mysql_fetch_row($result))
{
echo $row[0] ;
echo $row[1];
}
?>
+ mysql_fetch_array() :
Hm tr v mt mng l gi tr ca mt bng ghi hin ti, sau
hm s tr ti bng ghi tip theo cho ti khi gp bng ghi cui cng
hm
tr
v
gi tr false.
C php :
array mysql_fetch_array( int result_identifier [, int
result_type] );
Trong : result_identifier l m s tr v ca hm
mysql_query()
hoc mysql_db_query() .
truy xut n cc thnh phn ca
ct :
tn_bin_mng[tn_trng];
result_type l mt hng s c th nhn cc gi tr sau:

-MYSQL_NUM : ch tr li mt mng cha cc ch s l s


(ging nh hm mysql_fetch_row() )
-MYSQL_ASSOC: ch tr li mt mng lin kt
41

-MYSQL_BOTH : tr li mng cha ng cc ch s gm c cc


con s v ch s lin kt .
Hm ny l s m rng ca hm mysql_fetch_row(). N cho php
truy cp trng d liu ca mng kt qu khng ch thng qua cc ch
s l cc s m chng c th l tn ca cc trng d liu. iu ny lm
cho vic lp
trnh n gin v chnh xc hn.
V d:
<?php
$mysql

select

id,

name

from

ds_thanhvien; $link = mysql_connect($host,


$user,

$password);

$result

mysql_db_query(php, $mysql);
while ($row = mysql_fetch_array($result)) {
echo user_id: . $row[id] .<BR>\n;
echo user_id: . $row[0] .<BR>\n;
echo
user_name:
$row[name] .<BR>\n; echo user_name:
$row[1] .<BR>\n;

.
.

}
mysql_free_result ($result);
?>
+ mysql_fetch_object() : Hm tr v mt i tng l gi tr ca mt
bng ghi hin thi. Sau hm s tr ti bng ghi tip theo cho ti khi
gp bng ghi cui cng hm tr v gi tr false. truy xut ti cc gi tr
ca ct ta vit
tn_object->tn_ct .
C php :
object mysql_fetch_object(int result_identifier);
Trong : result_identifier l m s tr v ca hm
mysql_query() hoc mysql_db_query() .
V d :

42

<?php
$mysql = select id, name from
ds_thanhvien;
$link = mysql_connect($host, $user,
$password); $result =
mysql_db_query(php, $mysql);
while ($row = mysql_fetch_object($result)) {
echo $row->id ;
echo $row->name;
}
?>
+mysql_fetch_assoc() :ly v mt dng kt qu nh l mt mng lin
kt .
c php: array mysql_fetch_assoc(int result_identifier)
Trong : result_identifier l m s tr v ca hm
mysql_query() hoc mysql_db_query() .
Hm tr v mt mng tng ng vi mt bn ghi c ly v v
tr li FALSE nu khng c bn ghi no. Hm ny tng ng vi
hm
array

mysql_fetch_array()

vi

tham

result_type

MYSQL_ASSOC
v d :
<?php
$mysql = select id, name from
ds_thanhvien;
$link = mysql_connect($host, $user,
$password); $result =
mysql_db_query(php, $mysql);
while ($row = mysql_fetch_assoc($result)) {
echo $row[id];

echo $row[name];
}
?>

43

+mysql_data_seek()
Di chuyn con tr bn trong tp kt qu (c c sau khi cu
truy vn SELECT c thc hin)
C php: bool mysql_data_seek(int result_identifier, int
row_number);
Trong : result_identifier l m s tr v ca hm
mysql_query(),
mysql_db_query(), mysql_list_tables(), mysql_list_dbs() .
row_number l ch s ca bn ghi m cn t con tr vo
. Hm tr v true nu thnh cng, false nu li .
Hm ny s di chuyn con tr bn trong tp kt qu (c ch r
bi tham i result_identifier) n dng c m bng tham i
row_number.
Cc dng trong tp kt qu c bt u t 0
V d:
<?php
$link = mysql_pconnect ($host, $user,
$password) or die ("Could not connect");
$query = "SELECT last_name, first_name FROM
friends"; $result = mysql_db_query (php,$query)
or die ("Query failed");
# fetch rows in reverse order
for ($i = mysql_num_rows ($result) - 1; $i >=0;
$i--) { if (! Mysql_data_seek ($result, $i)) {
printf ("Cannot seek to row %d\n",
$i); continue;
}
if(!($row
=
mysql_fetch_object
($result))) continue;
}

printf ("%s %s<BR>\n", $row->last_name, $row->first_name);

mysql_free_result ($result);
?>

44

+ mysql_num_rows() :tr li s dng trong result_identifier (ni


cha kt qu ca cu lnh SQL c thc hin)
c php: mysql_num_rows(int result_identifier) ;
Trong : result_identifier l m s tr v ca hm
mysql_query(),
mysql_db_query(),
mysql_list_tables(),
mysql_list_dbs() .
+mysql_affected_rows()
c php : int mysql_affected_rows(int [link_identifier]) ;
Trong :int link_identifier l m s nhn dng, n phi c thc
hin trong hm mysql_select_db() trc .
Hm tr v s dng b tc ng bi mt cu truy vn SQL :INSERT,
UPDATE, DELETE trc theo tham s link_identifier. Nu
link_identifier khng c ch nh th m kt ni trc s c ch nh.
Ch :
- Nu cu lnh SQL trc l DELETE m khng c mnh WHERE
th ton b cc bn ghi trong bng b xo nhng hm
mysql_affected_rows() s tr v gin tr 0.
-Hm ny khng c tc dng i vi cu lnh truy vn SELECT. ly
c s dng tr v (s dng b tc ng) bi cu lnh SELECT ta
dng
hm mysql_num_rows().
+mysql_result() : ly d liu t result_identifier
c php : mixed mysql_result(int result_identifier, int row, mixed
[field]);
Trong : result_identifier l m s tr v ca hm
mysql_query(),
mysql_db_query(), mysql_list_tables(), mysql_list_dbs() .
row l bn ghi m ta s ly d liu
field l trng trong dng row m ta s ly d liu .
Cc tham s result_identifier v row phi c, cn tham field
l ty chn. Hm s tr li cc ni dung ca dng row v ct field t
tp kt qu c ch nh bi bin result_identifier. Nu i s field
khng c ch nh r th trng tip theo ca bn ghi s c tr

v .

45

V d:
<?php
$mysql = select id, name from
ds_thanhvien; $link = mysql_connect($host,
$user, $password); $result =
mysql_db_query(php, $mysql);
echo mysql_result($result, 0, id) <BR>\n;
echo

mysql_result($result, 0, name)

<BR>\n;
?>
+mysql_free_result() : Hm gii phng vng b nh c lin
kt vi result_identifier .
c php: mysql_free_result(int result_identifier) ;
Trong : result_identifier l m s tr v ca hm
mysql_query(),
mysql_db_query(),
mysql_list_tables(),
mysql_list_dbs() .
Hm ny ch c dng nu nh bn nh gi thy rng kch bn
ca bn s dng qu nhiu b nh khi ang chy. Gi hm ny trn
mt trnh x l kt qu s gii phng ton b d liu lin kt trong b
nh .
Ngoi ra cn cc hm khc:
string mysql_tablename (int result_identifier, int i)
Hm tr li tn ca bng/csdl ti ch s i trong result_identifier.
string mysql_field_name (int result_identifier, int field_index)
Hm tr li tn ca trng ti v tr field_index trong m
result_identifier int mysql_list_dbs ([int link_identifier])
Hm tr li mt result_identifier l danh sch bin CSDL trn MySQL
Server nu thnh cng, li tr v false .
int mysql_list_tables (string database [, int link_identifier])
Hm tr v danh sch tt c cc bng trong mt CSDL MySQL, thnh

cng tr v mt result identifier, gi tr false nu c li .


46

int mysql_list_fields (string database_name, string table_name [,


int link_identifier])
Hm tr v thng tin lin quan n mt bng d
liu. int mysql_num_fields (int result_identifier)
Tr v s trng trong tp kt qu .
int mysql_num_rows (int result_identifier)
Tr v s bn ghi trong tp kt qu, hm ny ch c gi i vi cc cu
lnh SELECT , ly li s bn ghi c tr li t cc lnh :INSERT,
UPDATE hoc DELETE, dng mysql_affected_rows().
string mysql_field_type (int result_identifier, int field_index)
Hm tr v kiu d liu ca trng ti v tr field_index trong
m result_identifier .
int mysql_field_len (int result_identifier, int field_offset)
Hm tr v di ca trng c ch nh thng qua tham s
field_offset . array mysql_fetch_lengths (int result_identifier)
tr v mt mng tng ng vi cc di ca mi trng trong bn
ghi c ly v bi hm mysql_fetch_row() hoc false nu c li.
int mysql_errno ([int link_identifier])
Hm tr v m li t hm thao tc CSDL MySQL trc ,tr v gi tr 0
nu khng c li .
string mysql_error ([int link_identifier])
Hm tr v xu thng bo li t hm thao tc CSDL MySQL trc,
tr v xu rng nu khng c li .
object

mysql_fetch_field

(int

result_identifier

[,

int

field_offset])
Ly thng tin v trng t tp kt qu ri tr li nh mt i
tng.

47

XI. Session v Cookie


1. Session l g ?
HTTP l giao thc khng c xy dng theo cch c th lu gi c
trng thi gia hai ln giao dch. Khi mt ngi dng yu cu truy nhp
mt
trang Web, ri sau ngi dng ny li tip tc yu cu truy nhp
i
vi
trang Web khc th HTTP khng th bit c rng l hai yu cu
t
cng
mt ngi dng.
tng ca vic iu khin phin lm vic l c th lu vt ca mt
ngi dng trong sut mt phin lm vic.
Nu chng ta lm c iu ny th s d dng cung cp mt truy
nhp cho ngi dng, t ta c th lu vt trng thi ca ngi
dng v c th thc hin vic mua bn trn mng.
Session trong PHP c iu khin bi mt gi tr ID duy nht gi l
sessionID, gi tr ny s c t ng sinh ra v m ha. SessionID
c
sinh ra bi PHP v c lu tr pha client trong sut mt phin giao
dch.
N c th c lu tr trn cc Cookie my ngi dng hay
truyn
ln
cc
URL.
SessionID c tc dng nh mt kho bn c th ng k nhng bin
c
bit gi l bin session. Ni dung ca nhng bin ny c cha trn
Server. SessionID l nhng thng tin ch thy c pha client. Nu ti
thi im
no ca mt kt ni n trang Web ca bn, sessionID c th thy
c
trn cookie hay URL, bn c th truy nhp nhng bin session ch trn
Server phin lm vic .
2) Cookie l g ?
Cookie l nhng mu tin nh m trang script c th cha trn cc my
khch
(client). Bn c th thit lp mt cookie trn mt my ngi dng
bng
cch
gi mt HTTP header c cha d liu theo dng sau:
Set-Cookie:Name=VALUE;[expires=DATE;]

[path=PATH;] [domain=DOMAIN_NAME;][secure]
cu lnh ny s to ra mt cookie c tn gi l NAME vi gi tr l
VALUE.
Trng expires s thit lp ngy m cookie s ht hiu lc, path v
domain
c th c s dng ch nh cc URL (ni m cookie s c gi
i). T

48

kho secure c ngha l cookie s khng gi i trn qu mt kt ni


HTTP
chun.
Khi mt browser kt ni ti mt URL, trc tin n kim tra cc cookie
c lu tr trn my. Nu c bt k mt cookie no c lin quan n
a ch URL va c kt ni, chng s c truyn tr li cho server.
3) Thit lp cc cookie t PHP
Ta c th thit lp cc cookie trong PHP bng cch s dng hm:
int setcookie (string name [,string value [,int expire [,string path
[,string domain [, int secure]]]]]);
Nhng tham i ca hm tng ng vi nhng tham i ca SetCookie header trn.
Nu ta thit lp cookie nh sau:
setcookie ("TestCookie", "Test Value");
th khi ngi dng n thm trang k tip trong site ca ta (hoc
reload trang
hin ti) ta s phi truy nhp vo bin vi tn l "TestCookie" c cha
gi tr
l "Test Value", ta ch c th truy nhp ti n thng qua bin mng
$HTTP_COOKIE_VARS [] ca PHP .
Ta c th xo mt cookie bng cch gi li hm setcookie() vi tham
i
nh
sau:
tn ca cookie l tn ca cookie cn xo v khng c trng gi tr.
4) S dng kt hp cookie vi session
i vi cookie c mt s vn sau y:
Mt vi webrowser khng th truy cp c ti cc cookie (khng h tr
cookie) v mt s ngi dng khng c cc cookie trn browser ca
h. y l l do PHP s dng c hai cch thc :cookie v URL
method.
Khi s dng PHP session, ta s khng phi thit lp cc cookie, nhng
hm session s lu gi nhng thng tin ny cho chng ta.
xem ni dung ca cc cookie c thit lp bi session ta s
dng
hm:
session_get_cookie_params(). Hm ny s tr v mt mng lin kt

m cc phn t ca mng cha cc thng tin nh: lifetime, path,


domain,.. .
49

thit lp cc tham s cho session cookie ta dng hm:


void session_set_cookie_params (int lifetime [, string path [,
string domain]])
5) Lu gi sessionID
PHP s s dng cc cookie mc nh cng vi session. Nu c th c,
mt cookie s c thit lp cha SessionID.
Mt cch s dng cc SessionID trn URL l dch PHP cng vi
la chn -enable-tran-sid.
Cch na l ta c th a sessionID vo trong th link. SessionID c
cha trong hng SID. lm c iu ny, ta thm vo cui th link
hng SID dng n nh l phng thc GET.
V d:
<A HREF = link.php?<?=SID?>>
Hng SID lm vic c nh trn ch khi ta cu hnh PHP cng
vi --enable-track-vars.
6) Thc thi nhng phin lm vic n gin.
Nhng bc c bn ca vic s dng
session: + Bt u mt Session
+ ng k nhng bin Session
+ S dng bin Session
+ Hu b bin Session v kt thc Session
6.1 Bt u mt Session
Cch n gin nht bt u mt Session l dng hm:
Bool Session_start();
Hm ny s kim tra xem c mt Session ID no c to ra hay
cha. Nu cha th n s to ra mt Session ID, cn nu tn ti mt
Session ID th thc cht n ch ly ra nhng bin Session ta c th
dng n. Hm tr v gi tr TRUE nu thnh cng ,ngc li tr v gi tr
FALSE.

50

Chng ta cng c th bt u mt Session bng cch cu hnh PHP


n t ng bt u khi c ai thm trang Web ca ta. iu ny c
th lm c nu ta chn session. auto_start trong file
c:\Windows\php.ini
Mt Session cng s c bt u khi ta ng k mt bin Session.
6.2 ng k nhng bin Session
cho mt bin c th lu du thng tin t mt trang script ny sang
trang script khc, ta cn phi ng k n bng cch gi hm:
bool session_register(mixed VarName [,mixed...]);
Vic ng k ny s lu tr tn bin v ghi gi tr ca bin cho n
khi phin giao dch kt thc hoc khi ta hu b (deregister) vic ng
k bin .
V d:
ng k bin $Var_name ta vit nh
sau: $Var_name= 5;
session_register(Var_name);// khng nn s dng k t $ trong
ng k mt bin
6.3 S dng bin Session
a mt bin Session vo trong phm vi m n c th c s dng,
ta cn phi khi to mt Session bng mt trong nhng cch nu trn.
Sau , ta c th truy cp c nhng bin ny. Nu ng k bin
ny l ton cc bng cch s dng hm register_global(), th ta c th
truy nhp bin bnh thng thng qua tn bin, v d : $Var_name ;
Nu khng khai bo bin l ton cc th ta phi truy nhp nhng bin
Session
thng qua mng lin kt $HTTP_SESSION_VARS(Var_name);
kim tra xem mt bin c ng k l bin Session hay cha
ta dng hm: bool session_is_registered (string name);
Hm ny tr v gi tr TRUE nu bin c ng k, ngc li
tr v gi tr FALSE.
Ta cng c th kim tra mt bin c l bin Session bng cch kim
tra
mng lin kt $HTTP_SESSION_VARS() v s tn ti ca bin.

51

6.4 Hu b bin Session v kt thc Session


Khi mun kt thc mt bin Session, ta c th hu b ng k ca
bin bng hm : bool session_unregister (string name) ;
Trong : name l tn bin ta mun hu ng k (tn ny khng cn
c
k
t $)
Hm tr v gi tr TRUE nu thnh cng ,ngc li tr v gi tr
FALSE.
Hm ny ch c th hu ng k ca mt bin Session ti mt thi
im.
hu tt c cc bin Session hin ti, ta dng hm: void session _unset
( ) ; kt thc mt Session ta dng hm:s
bool session_destroy () ;
Hm ny s xo i SessionID v hy tt c nhng d liu lin quan n
Session ny. Hm tr v gi tr TRUE nu thnh cng, ngc li tr v
gi tr FALSE.
Ta nn hy tt c cc bin Session trc khi kt thc mt Session.

52

Chng III : Phng php Fast Template


trong
PHP
I. Cc k thut mu ph bin
Cc mu c th c dng nu nh bn ang thc hin
mt
site
thng xuyn s dng li cc thnh phn .Trong phm vi ca
PHP ,cc
mu y ni n HTML. Khng dng cc mu ,mt web site
phc tp s c cu trc rt nng.
gii quyt vn trn ,nhiu k thut mu tn ti, nhng
c th hu ch trong mt s trng hp. Chng ta gii thiu qua
mt s k thut c s dng thng xuyn .
Code/
Name

Embedded
PHP
Separating
common
parts

FastTemplate

HTML
mixed

Yes

Yes

No

HTML
structure Advantages
Defined
in PHP
Yes

No

No

Fastand
easy
Fast and
easy,
Reuseof
certain
pasts
Abstracts
HTML
completely
from
coding,
easy
to adapt to
new needs

Disadvantages

Useful for

Leadsto unreadable
scrips, noreuse of
Quick and
existing code,hardto Smallscripts
maintain
Leadsto unreadable Web sites
scripts, often hard with LOC <
to maintain
1000

Complex

Web sites
with LOC >
1000

53

Vic s dng cc mu trong cc trnh ng dng


1. Embedded PHP
Chng ta c th nhng cc cu lnh PHP vo trong HTML. Mt
v d in hnh ca cch thc trn :
<HTML>
<HEAD>
<TITLE>powers</TITLE>
</HEAD>
<BODY
BGCOLOR=black
TEXT=white>
<H1>powers</H1>
<TABLE>
<TR>
<TH>i</TH>
<TH>i^i</TH>
</TR>
<?php
for ($i= 0 ; $i< 10 ; $i++) {
echo
<TR><TD>$i</TD><TD>.pow($i,
$i).</TD></TR>\n;
}
?>
</TABLE>
</BODY>
</ HTML >
Phng php ny c dng kh ph bin vi nhng ngi
bt u hc lp trnh PHP. Ti mt lc no ,nhng ngi mi
lp trnh bng phng php nhng tin ti s thnh tho cc mc
cao hn, nhng tht ng tic, cch lp trnh ny li ngn cn
iu .
2. Separating common parts
54

Mc d k thut ny c s dng li cc m code/HTML v vic thay


i cng d dng hn ,nhng n vn tha hng hu ht cc nhc
im ca phng php PHP nhng .
Cch lm thng thng l bt u vi cc HTML header v footer,
chng c vit thnh cc hm. Cc hm ny c th c gi khi cn
n chng v do linh hot hn khi s dng. S thay i cc
hm s c phn nh trong tt c cc trng hp.
Ta tch v d PHP nhng trn ra hai file .
Tp prepend.inc cha hai hm :hin th mt HTML header v mt
HTML
footer .
<?php
//prepend.inc
function CommonHeader($title)
{
?>
<HTML>
<HEAD>
<TITLE><?php

echo $title

></TITLE> </HEAD>
<BODY
TEXT=white>

BGCOLOR=black
<H1><?php

$title ?></H1>
<?php
}
function CommonFooter() {
?>
</TABLE>
</BODY>
</HTML>
<?php
}
?>
\
Tp main.php s dng tp prepend.inc

echo

55

<?php includeprepend.inc;?>
<?php CommonHeader( power ); ?
> <TABLE>
<TR>
<TH>i</TH>
<TH>i^i</TH>
</TR>
<?php
for ($i= 0 ; $i< 10 ; $i++) {
echo <TR><TD>$i</TD><TD>.pow($i,$i). </TD></TR>\n;
}
?>
</TABLE>
<?php CommonFooter(); ?>
3. FastTemplate
Trong phn ny chng ta cng tm hiu v phng php
thit k Web trong PHP l FastTemplate. y l phng php hay,
n c gn km vi cc gi ng dng ca PHP, n c xy
dng trong tp tin c tn class. FastTemplate.php .
Mc ch ca phng php ny l gip cho chng trnh vit bng
PHP
c nhiu giao din khc nhau trn cng mt c s m, v lm
gim
khi
lng cng vic do chng trnh c tch ra lm hai phn :
phn
vit
cc on m (code) v phn thit k giao din cho chng trnh.
Phn
vit cc on m s tnh ton d liu v th hin trn cc trang
HTML
thng qua cc bin FastTemplate. Phn giao din s thit k giao
din
cho chng trnh bng ngn ng HTML. Trong phn ny chng ta c
th
lng vo trang HTML cc ngn ng nh Java Applet,
JavaScript,
...
cho
trang web thm sinh ng. Vic thm vo trang HTML nhng
on
m
ny khng lm nh hng ti phn on m PHP. Khi , v tr
no

trn trang web cn th hin cc kt qu tnh ton t on m


th
s
s
dng cc bin FastTemplate th hin.

56

II. Phng php FastTemplate


1. Bin FastTemplate
Bin FastTemplate l g ?
Cc bin FastTemplate c cu trc nh sau :
{TEN_BIEN_FASTTEMPLATE}
Bin c t trong du ng m ngoc nhn, tn bin gia, tn
c th l ch hoa hoc ch thng. Tuy nhin trong phn on
m PHP bn cng phi vit ging nh vy.
2. V tr t bin FastTemplate
Cc bin FastTemplatse c th t bt k u trong trang HTML.
N c th l bin th hin thng tin trn cc trang HTML khi c
browser hin th hoc cc bin s thm vo cc on m HTML .
V d : ta t tn tp
vidu_template.tpl <HTML>
<HEAD>
<TITLE>{TITLE}</TITLE>
</HEAD>
<BODY>
{CONTENT}
</BODY>
</HTML>

Trong v d trn c hai bin FastTemplate l {TITLE} v


{CONTENT}. Bin {CONTENT} s th hin thng tin trn trang
web
khi
c hin th, bin {TITLE} c thm vo nh mt thnh phn
ca
m
HTML .
3. Mt v d minh ha
Theo v d trn chng ta c tp vidu_template.tpl, by gi
chng ta i xy dng on script sau :

57

<?php
include class.FastTemplate.php;
# khai bo mt i tng thuc lp
FastTemplate $tpl = new FastTemplate(.);
# nh ngha mt bn cc tp FastTemplate
$tpl->set_filenames(array(body

=>

vidu_template.tpl )); # Gn cc gi tr cho bin


FastTemplate
$tpl->assign_vars(array(
TITLE => Vi du,
CONTENT => Ni dung ca trang web
)); # Cho hin trang web ny
$tpl->pparse(body);
?>
4. Bn bc cho mt trang web .
Trong mt script cn thc hin bn bc theo th t sau :
Bc 1 : Khai bo mt i tng thuc lp FastTemplate
Bc 2 : Gn cc tp cha m HTML (tp ny c phn m rng
khng nht thit l *.htm) cho cc phn t ca mng c nh ngha
bi
phng
thc set_filenames() ( bc ny c gi l nh ngha mt bn cc
tp
FastTemplate ) .
Bc 3 : Gn gi tr cho cc bin FastTemplate trong cc
tp .
Bc 4 : Cho hin trang web bng phng thc
pparse(tn_trang_web)
Ch :
+ Bc 2: Trong nh ngha mt bn cc tp FastTemplate c
th nhiu tp c gn .
+ Bc 4: Mi ln gi phng thc pparse(); ch c mt

tp FastTemplate.
58

+ Cc bc 1,2,3,4 c th lp li nhiu ln .
+ Th t gi phng thc pparse(); l rt quan trng v n nh
hng n cch th hin ca trang web.
5. Khi FastTemplate
Thng tin trn trang web c th c th hin di dng bng,
vi s hng khng xc nh do FastTemplate c h tr khi
FastTemplate. Khi FastTemplate s lp i lp li mt on HTML no
khi c nh du khi. Xt v d sau :
Hy thc hin php tnh 2a vi a = 1, ..., n. Kt qu c th
hin bi mt bng gm hai ct, ct gi tr ca a v ct kt qu ca
php tnh 2a.
Chng ta to tp
tinh_2_mu.htm
<html>
<head>
<title>Tinh 2 mu a</title>
</head>
<body>
<table border="1"
width="100%">
<tr>
<td width="50%">
<p align="center">Gia tri
a</td> <td width="50%">
<p
align="center">Tinh
2</td> </tr>
<!-- BEGIN block -->
<tr>
<td width="50%">
<p align="center">{block.GIATRI}</td>
<td width="50%">
<p align="center">{block.KETQUA}</td>

59

</tr>
<!-- END block -->
</table>
</body>
</html>
Ta thy tp ny to mt bng hai hng hai ct, hng trn l tiu
ca
cc ct, hng di ct th nht l gi tr ca a v ct th hai l kt qu
ca
php tnh 2a. Hng di c bt u bi kho <!-- BEGIN block -->
v kt
thc bi kho <!-- END block-->. Hai kho ny cho bit phn bn trong
s b
lp (block y l tn kho), cc bin FastTemplate bn trong c dng
{tenkhoa.TEN_BEN}.
on PHP Script s nh sau :
<?php
include "class.FastTemplate.php";
$tpl = new FastTemplate(".");
$tpl->set_filenames(array(
'tinh_2_mu_a' => 'tinh_2_mu.htm'
));
$n = 10;
for ($i = 1 ; $i <= $n ; $i++)
$tpl>assign_block_vars("block",array( 'G
IATRI' => $i,
'KETQUA' => pow(2, $i)
));
$tpl->pparse("tinh_2_mu_a");
?>
Kt qu khi chy chng trnh nh hnh v.

60

Phn II : H C S D LIU MYSQL


Chng I.

Gii thiu Ngn ng MySQL

I. Gii thiu chung


MySQL rt phc tp, nhng giao din SQL trc gic v d hc.
Trong
chng ny chng ta m t khi qut v cc lnh, cc kiu d
liu
v
cc
hm m chng ta cn bin s dng Mysql mt cch c hiu qu
v
c
hiu sut cao.
Chng ny cung cp tt c cc hm tham kho trong Mysql. s
dng
chng ny c hiu qu bn c th tm n hng lot cc bng
c
lit
k.
Cc u im ca MySQL:
MySQL l mt h qun tr nh, bo mt, v rt d s dng,
thng
c s dng cho cc ng dng nh v trung bnh. N c s
dng cho cc ng dng client / server vi my ch mnh nh
UNIX, Windows NT v Windows 95/98, v c bit trn my
ch
UNIX .
MySQL h tr cc im vo l ANSI SQL92 v ODBC mc 0-2
SQL chun.
MySQL h tr nhiu ngn ng cho vic thng bo li nh :
Czec,
Dutc, English, Estonian, French, German, Hungarian, Italian,
Norwegian Nynorsk, Polish, Portuguese, Spanish and Swedish.
Ngn ng c h tr mc nh cho d liu l ISO-8859-1
(Latin1), mun thay i phi sa trong m ngun .
Ngn ng lp trnh s dng vit cc hm API thm nhp

s
d liu MySQL c th l C, Perl, PHP.. .

Cc bng (table) trong c s d liu MySQL c kch thc rt


ln
v c lu th mc Datas. Kch thc ln nht ca mt
bng ti
thiu l 4GB v n cn ph thuc v kch thc ln nht ca mt
file do h iu hnh quy nh .

61

C s d liu MySQL rt d qun l v c tc x l cao


hn ti
ba bn ln so vi cc h qun tr c s d liu khc.
MySQL l mt h qun tr c s d liu m hnh quan h, n c
m
ngun m. N c cung cp min ph trn cc my ch UNIX,
OS/2 v c trn Windows.
Bn cnh cc u im trn MySQL cng c mt vi nhc im :
MySQl khng cho php thc hin cc cu lnh SQL select truy
vn
con. V d : SELECT deptno, ename, sal
FROM emp x
WHERE sal > (SELECT AVG(sal)
FROM emp
WHERE x.deptno = deptno)
ORDER BY deptno

MySQL khng h tr Stored Procedures, Triggers,


Transactions,
Foreign Keys, v Views nh cc h qun tr c s d liu
khc .
II .Cu trc ngn ng
1. a ra mt xu v mt s nh th no
Mc ny m t nhng cch khc nhau a ra xu v s trong
Mysql. mc ny cng bao gm nhiu sc thi v ``gotchas'' iu m bn
c th gp khi i su vo cc kiu c bn trong Mysql.
2. Xu
Xu l mt dy k t, c t trong du nhy n hoc du
nhy
kp
(nu chy trong phng thc ANSI th xu ch c t
trong
du
nhy n)
V d: tri nng.
cho bui sng.
Trong mt xu, c s kt hp ca cc k t to nn cc k t c
bit.
Mi

k t c bit ny bt u bng du cho ngc ( \ ) c xem nh


k
t
escape .
Mysql nhn bit cc k t c bit sau:
\ 0 : k t 0 trong m ASCII.
\ : K t nhy n .
62

\ : K t nhy kp .
\ b : K t Backspace.
\n : K t xung dng mi.
\r : K t v u dng .
\t : Nhy (tab).
\z : K t 26 trong m ASCII. K t ny c th c m ho
ng cui file trong Windows.
\\ : K t cho ngc \ .
\% : K t % .
\ _ : K t gch di _ .
ch : nu nh s dng k t \% hoc k t gch di \ _ trong
mt s trng hp c th tr v \% v \ _ ch khng phi l % v _ .
* c mt s cch xu gm c du nhy :
- mt du nhy n ( ) nm trong mt xu c nh du bi du
nhy n th phi vit l: .
- mt du nhy kp ( ) nm trong mt xu c nh du bi du
nhy n th phi vit l: .
- c th t k t (\) trc k t nh du .
- mt du nhy n trong cp du nhy kp a ra xu cha du nhy
n, mt du nhy kp trong cp du nhy n a ra xu
cha du nhy kp.
- V d :
mysql> SELECT 'hello', '"hello"', '""hello""', 'hel''lo','\'hello';
| hello | "hello" | ""hello"" | hel'lo | 'hello |
mysql> SELECT "hello", "'hello'", "''hello''", "hel""lo",
"\"hello"; | hello | 'hello' | ''hello'' | hel"lo | "hello |
mysql> SELECT "This\nIs\nFour\nlines";
| This
Is
Four
lines |

63

nu bn mun chn d liu nh phn vo trong ct BLOB. Nhng k t


sau phi c th hin di dng nhng k t c bit :
- NUL : ASCII 0. phi c th hin \ 0 .
- \ : ASCII 92. du gch ngc phi c th hin \\ .
- :ASCII 39. du nhy n phi c th hin \ .
- : ASCII 34. du nhy kp phi c th hin \ .
- nu bit m C, c th s dng hm CAPI l Mysql-escape-string()
ESC k t bng cu lnh INSERT.
- Nn s dng hm ESC i vi nhng xu cha k t c bit c lit
k trn.
3. S (Numbers)
S bao gm s nguyn v s thc .
S nguyn c biu din bng mt dy s. Cn s thc s dng
du chm phn cch phn thp phn .
Du gch di c t trc s ch s
m. V d:
1221
0
32
V d cho s thc:
94.42
32032.6809e10
48.00
ch : s nguyn c s dng trong ng cnh s thc c
chuyn thnh s thc c gi tr ngang bng
v d : float 0 0.0
float 56 -> 56.0
Nhng gi tr h Hexa (h 16)
Mysql h tr cc gi tr h Hexa. Trong ng cnh s th chng
ging
nh mt s nguyn. Trong ng cnh xu th chng ging nh mt
xu nh
phn m mi cp s nguyn Hexa c chuyn thnh mt k t .
V d:
mysql> SELECT x'FF'
-> 255
mysql> SELECT 0xa0;
-> 10
mysql> select 0x5061756c;
-> Paul
64

v d trn khi vit mt s di dng Hexa bn phi in vo vo


trc
s
chui x hoc 0x. C php x xu Hexa da trn ANSISQL,
v
c
php 0x da trn ODBC. Xu h Hexa thng s dng ODBC a
gi
tr
cho ct BLOB C th chuyn mt xu hoc s thnh h Hexa bng
hm
HEX().
4. Gi tr NULL
Gi tr NULL c ngha l khng c d liu(no data) khc vi
gi tr 0 i vi kiu s v xu rng i vi kiu xu .
Trong khun dng xut hoc nhp File d liu NULL c th c
th
hin bng \N (nh LOAD DATA INFILE, SELECT...INTO OUTFILE).
5. Tn ca C s d liu, bng, ch s ct v b danh
Tn ca c s d liu, bng, ch s ct v b danh tt c u tun
theo
mt qui lut chung trong Mysql. Nhng ch rng qui lut
ny

c thay i bt u vi Mysql Version 3.23.6 khi chng ta


da
vo
li ch thch cho vic nhn bit c s d liu, bng v tn ct vi
du

. s lm vic nhn ra li ch thch nu bn chy trong


ch

ANSI .
nh danh di
(Identifier)
Database
64
(c s dliu)
Table
64
(Bng)
Column
64
(Ct)
Alias
256
(Bdanh)

Cc k t cho php
Tt c cc k t cho php trong th mc
ngoi tr / v .
Tt c cc k t cho php vi tn File ngoi
tr / v .
Cho php tt c cc k t
Cho php tt c cc k t

Ch : bng trn nh danh khng th c k t nh du,


ASCII(0) hoc ASCII(255) .

Nu nh danh l mt t b hn ch hoc trong c cha cc k


t
c bit th bn phi s dng du nhy n ch thch khi s
dng
chng .
V d: SELECT * from `select` where `select`.id >
100;
Trong phin bn trc ca Mysql, lut t tn nh
sau :

65

- Mt tn gm cc k t trong bng m, cng cho php k t gch di


_ v $.
- Tn c th bt u bi tt c cc k t hp php, trong thc t
tn c
th bt u bng mt s (iu ny khc nhiu vi h c s d
liu )tuy
nhin tn khng ch gm mt s .
- Khng c s dng k t . Trong tn bi v k t c
s
dng
m rng khun dng truy nhp n ct (xem bng di
y).
Chng ta khng nn dng nhng tn nh 1e bi v mt biu
thc
nh
1e1th rt m h, n c th c bin dch l mt biu thc 1e1
hoc
l
s 1e1.
Trong Mysql ta c th lin h ti mt ct bng vic s dng nhng
cch
sau:
Ct tham chiu
Col_name

ngha
Ct col_name t bng s dng trong cu truy vn
cha ct vi tn ny.
Tbl_name.col_name Ct col_name t bng tbl_name ca c s d liu
hin thi .
Db_name.tbl_name. Ct col_name t bng tbl_name ca c s d liu
col_name Db_name.
column_name
Mt ct c cha k t c bit hoc t kho
Bn cn phi ch r tbl_name hoc db_name.tbl_name i vi nhng
ct c cng tn trong nhiu bng ca c s d liu, hoc bng c cng
tn trong cc c s d liu khc nhau trnh s nhp nhng .
V d : gi s mi bng T1 ,T2 ch mt ct C bn c th ly C
trong
mt
lnh SELECT s dng c T1 v T2. Trong trng hp ny C nhp nhng
bi
v n khng duy nht gia cc bng c s dng trong cu lnh.
Bn
phi
ch ra tn bng bng cch vit T1.C hoc T2.C. tng t nu bn ly
t
mt
bng T trong c s d liu DB1 v t bng T trong c s d liu
DB2,
bn

phi tham chiu n ct trong nhng bng nh sau :


DB1.T.col_name
v
DB2.T.col_name.
C php .Tbl_name c ngha l bng Tbl_name nm trong c s d liu
hin thi .c php ny c chp nhn cho tng thch ODBC
bi v mt s chng trnh ODBC thm vo u tn bng mt
du chm .
6. Phn bit ch hoa v ch thng i vi tn trong Mysql :

66

Trong Mysql tn c s d liu, bng trong Windows th khng phn


bit ch hoa v ch thng, cn trong Unix th c phn bit ch hoa
v ch thng . Ch : mc d trong windows khng phn bit ch
hoa v ch thng, bn cng khng nn dng tn c s d liu,
bng vi cc trng hp khc nhau trong cng mt cu truy vn .
V d :
mysql>
SELECT
*
FROM
my_table
WHERE
MY_TABLE.col=1; cu lnh trn s khng thc hin c .
Tn ct khng phn bit ch hoa v ch thng trong tt c cc
trng hp . B danh trn bng phn bit ch hoa v ch thng
V d: mysql> SELECT col_name FROM tbl_name AS a
WHERE a.col_name = 1 OR A.col_name = 2;
Cu lnh trn s khng thc hin c v b danh phn bit a v A
B danh trn ct s khng phn bit ch hoa v ch thng.
Nu bn mun truy vn thc hin c trn bng th chp nhn
mt qui c lun lun to ra tn c s d liu v tn bng s dng
ch thng. Mt cch trnh vn ny l s bt u mysql vi
-0 lower_case_table_names = 1, Theo mc nh ty chn ny l
1 trn Windows v 0 trn Unix. Nu lower_case_table_names l 1
MySQL s chuyn i tt c cc tn bng v ch thng ,Ch rng
nu bn thay i ty chn ny, bn cn trc ht chuyn i
nhng tn bng c ca bn v ch thng trc khi bt u
mysql.
7. Bin ngi s dng
Mysql h tr cc bin ring cng vi c php @variable name. Tn
bin bao gm k t anpha t tp cc k t v thm vao k t _, $, v
.
Bin khng phi khi to, NULL khng xut hin trong bin, bin c
th cha s nguyn thc hoc gi tr xu. Tt c cc bin s t gii
phng vng nh khi chng thot ra.
Bn c th gn biu thc vo bin theo c php :
@variable:=expr
V d:
select @t1:=(@t2:=1)@t3:=4,@t1,@t2,@t3;
| @t1:=(@t2:=1)@t3:=4 | @t1 | @t2 | @t3 |
|

5|

5|

1|

4|

chng ta phi s dng c php:= gn bin, bi v du bng (= )


c s dng so snh .

67

bin c th c s dng trong mt biu thc lu rng iu


ny khng c s dng trong ng cnh mt s c yu cu r
rng nh trong mnh LIMIT ca lnh select hoc mnh
IGNORE number LINES ca lnh LOAD DATA .
ch : trong lnh SELECT mi biu thc ch nhn mt gi tr khi n
c gi cho ngi dng. iu ny cng ng trong mnh HAVING,
GROUP BY, ORDER BY. Bn khng th tham chiu ti mt biu thc
gm tp hp cc bin trong SELECT.
V d:
SELECT (@aa:=id) AS a, (@aa3) AS b FROM table_name HAVING b=5;
Cu lnh trn khng thc hin cbi v @aa s khng cha gi tr
hng hin ti tr phi g tr ca id thay cho ct c chp nhn trc .
8. Cc dng ch thch
Mysql cho php chn cc cu ch thch vo trong kch bn ca
Mysql, khi thc hin trnh thng dch s b qua tt c cc on vn bn
l cu ch thch Trong Mysql ch thch c t sau du : # dng ch
thch
-- dng ch thch
cch vit ny ch c tc dng trn mt dng .
dng cp k hiu sau : /* ....*/ chn cc cu ch thch, loi ch thch ny
c gi l ch thch khi .
v d: mysql> select 11;# ch thch trn mt dng
mysql> select 11; -- ch thch trn mt dng
mysql> select 1 /* ch thch khi*/
1; mysql> select 1
/*
ch thch trn nhiu dng
ch thch khi
*/
1;
lu rng ch thch - yu cu bn phi c t nht mt du cch sau --!
Mc d vy c vi hn ch trong cch ghi ch \*..*\ l:
- k t nhy n v nhy i dng ch s bt u ca mt xu
thm
ch s dng bn trong mt ch thch nu trong ch thch du nhy
th
nht khng ph hp vi du nhy th hai th h phn tch s
khng
nhn ra im kt thc ca ghi ch.
- du chm phy ( ; ) c dng bo kt thc ca mt cu
lnh
Mysql v sau du ( ; ) l s bt u ca cu lnh tip theo.

68

Chng II. Cc thnh phn ca My SQL


Trong phn ny chng ta gii thiu khi qut v cc kiu d liu
ca cc trng va cc thuc tnh v kiu trong mi loi d
liu.Sau l mt s kiu bng trong MySQL v cui cng l
mt s hm c bn c cung cp bi MySQL.
I.

Cc kiu d liu

Trong MySQL c cc kiu d liu sau:


Kiu s
Kiu k t (char,varchar,Blob,Text,Enum,Set)
Kiu xu.
Kiu ngy gi (Datetime,Date,TimeStamp,Time,year)
1. Kiu s
Kiu tinyint:
Khai bo TINYINT[Cm] [UNSGNED] [ZEROFIU].y l kiu
s nguyn vi gi tr rt nh:
-Nu khai bo vi t kho nusigned th gi tr m ct c
kiu ny c th nm trong khong 0 n 255.
-Nu khng c t kha nusiged th gi tr trong khong
-128 n 127
Kiu Smallint
Khai bo:Smallint [Cm] [nusiged] [zerofill].y l kiu s
nguyn c gi tr nh:
-Nu l s c du th gi tr nm trong khong-32768 n
32767
-Nu l s khng du th gi tr trong khong 0 n 65536.
Kiu Mediumint
Khai bo :Mediumint [cm] [nusiged] [zerofill] [(m)]
-Nuc du th gi tr nm trong khong -8388608
n 8388607.
-Nu l s c du th gi tr nm trong khong 0 n
16777215. Kiu Int:
Khai bo:Int:[Cm] [nusiged] [zerofill]
-Vi s c du gi tr trong khong -2147483648
n 2147483647
-Vi s khng du gi tr trong khong 0 n
429467295 Kiu Interger
Khai bo:interger [Cm] [nusiged] [zerofill].Tng t kiu INT.

69

Kiu Bigint
Khai bo :Bigint [Cm] [nusiged] [zerofill].y l kiu nguyn
m gi tr l rt ln.
-Vi s c du gi tr trong khong
-9223372036854775808 n
9223372036854775807.
-Vi s khng du gi tr trong khong 0 n
18446744073709551615
Note:tt c cc php ton s hc s dng s c du bigint hoc
double, v vy khng s dng s khng du ,m gi tr vt qu s
nguyn ln tc l nu nhn hai s nguyn ln th gi tr tr v s
vt qu s
nguyn ln c du.
Kiu float:
Khai bo:float (precision)[zerofill].i vi s thc chnh xc
n th chnh xc <24.i vi s thc chnh xc kp th
chnh xc <255.Float(x) ging kiu double,float nhng c v
s ch s phn thp phn cha c nh ngha
Precision:s ch s phn thp phn m float c th nhn.Float
[Cm,d] [zerofill]:y l s thc vi chnh xc kp vi m hin
th rng,d l s cc ch s phn thp phn.
Nu dng float khng c i hoc i <=24,th tng ng
dng s thc c chnh xc n.
Double [(Cm,d)] [zerofill]:s thc vi chnh xc kp vi m l

rng, d l s ch s phn thp phn.Nu dng double khng i


hocdng float(x) vi 25<=x<=53 thay cho mt s thc
chnh xc
kp.
Double precision [(Cm,d)][zerofill]
Real [(Cm,d)][zerofill] .tng t nh s double.
Decimal [(Cm,d)][zerofill] c coi nh mt kiu char,c
lu tr nh mt xu mi k t l mt k s ca gi tr cn lu
tr.
Nuneric [(Cm,d)][zerofill] tng t decimal.
2.Kiu ngy gi
2.1 Datime, Date, TimeStamp.
Cc kiu Datime, Data, TimeStamp c nhng c trng ring
nhng cng c mi lin quan.
C mt s Y2K chng ta tng bin i vi cc kiu thi
gian khng gian r rng trn
MySQL gii thch cc ngy cng vi gi tr nm mp
m theo quy lut sau:
-Gi tr nm trong khong 70-69 c chuyn sang nm 2000-

70

2069
1999.

-Gi tr nm trong khong 70-99 c chuyn sang nm 1970-

l v gi tr nm ta ch hai ch s, cn hai s trc


mc nh l nm 1900. lm cho khng nhm ln nm th phI
cung cp gi tr nm l bn s.MySQL lm iu ny.
Kiu datetime: y l kiu ngy gi c dng khi bn cn lu
tr thng tin c v ngy thng v thi gian.Gi tr ca n nm
trong khong 1000-01-10:00:00 n 9999-12-3123:59:59
MySQL hin th datatime theo nh dng:
yyyy-mm-dd hh:mm:ss nhng n cng cho php n nh gi tr
cho kiu ny bng dng s hoc xu.
Kiu Date c dng khi bn ch cn lu tr gi tr ngy thng.
MySQL truy xut v hin th gi tr DATE vi nh dng
yyyymm-dd
Gi tr trong khong 1000-01-01 n 9999-12-31c th
n inh bng s hoc xu.
Kiu TIMESTAMP [Cm]
Cung cp 1 kiu m bn c th dng nh du mt cch t
ng
i vi php INSERT hoc UPDATE cng vi ngy gi hin ti.Nu
c nhiu ct TIMESTAMP th ch ct u tin c cp nht mt
cch
t ng.
cp nht vo ct u nh vy cng phi tho mn cc
iu kin sau:
-Ct m cha c xc nh chi tit trong mnh
INSERT hocLOADDATAINFILE
-Ct m khng xc nh chi tit trong lnh UPDATE v mt
s ct khc thay i gi tr
-Bn t chi tit ct TIMESTAMP l ngy gi hin ti
bng cch n nh gi tr NULL
Cc ct khc c th c t thi gian v ngy thng hin ti.Ch
c vi ct gi tr NULL hoc NOW.Gi tr ca TIMESTAMP l t
197001-01:00:00:00.n nm 2037 th MySQL hin th TIMESTAMP
theo nh dng yyyy mm dd hh mm ss
yyyy mm dd hh mm ss.MySQL cng cho php s dng bng
xu hoc s.
Kiu TIME
MySQL nh dng gi tr thi gian l hh:mm:ss hoc
HHH:MM:SS
Nguyn nhn m phn gi c th ln hn ti v kiu TIME khng
ch
biu din thi gian trong 1ngy (gi phi <24) m n cn l
khong
thi gian gia hai s kin (c th >24 hoc thm ch l m).Gi

tr ca
71

n trong khong -838:59:59 ti


838:59:59 Kiu YEAR
C th nh dng bi hai hoc bn ch s, gi tr nm trong
khong 1901 n 2155 vi bn ch s.
Vi hai s th mc nh t 00-69 l 2000-2069 ,70 n 99 l
19701999
3.Kiu k t (String)
Kiu char: di ct char l c nh khi bn to bng. Gi tr
di trong khong 0-255 nu s k t in vo nh hn di quy
nh th n s t ng in vo k t trng.
Trong MySQL kiu char cho php bn to mt ct c dng
char(0),iu ny cng thun tin trong trng hp bn phi tun
theo
vi s phn mm c n ph thuc v s tn ti ca mt ct m
khng
thc s cn s dng gi tr. Cng tt trong trng hp bn cn
nh
ngha mt ct sao cho n c th nhn hai gi tr mt ct khai bo
char(0) n c th chim mt bit v c th nhn hai gi tr NULL
hoc

Kiu Varchar [national] varchar(m)[binary]. y l ct c
khai bo vi mt xu c di khng c nh nhng k t trng
s c hu khi lu tr gi tr, m nm trong khong 1-255.
value

Char(4)

ab
abcd
abcdefgh

ab
abcd
abcd

Storage
require
d
4bytes
4bytes
4bytes
4bytes

Varchar

ab
abcd
abcd

Storage
require
d
1bytes
3bytes
5bytes
5bytes

Kiu Blob v TEXT


-BLOB l i tng nh phn ln c th cha lng rt ln
cc d liu vi 4 kiu BLOB:TINYBLOB, BLOB, MEDIUMBLOB
v LONGBLOB.C 4 kiu TEXT l TINYTEXT,TEXT,
MEDIUMTEXT, v LONGTEXT
TINYBLOB,TINYTEXT:c rng ti a
l255 Blob v Text di ti a l 65535
k t.

Mediumblob,mediumtext: di ti a 16777125 k
t. Longblob,longtext: di ti a 424967295 k
t.
72

Ch : M hnh client/server gii hn bi 16Mb. Mt gi giao


tip trn mt hng nn khng th s dng ton b phm vi ca
kiu ny. Kiu ENUM(value1,value2,..)(kiu lit k). Mt i tng
xu ch c th c 1 gi tr chn t mt danh sch cc gi tr
value1,value2,..null hoc k t c bit.
Mt kiu lit k c gi tr ln nht l 65535 gi tr.
Kiu tp hp set(value1,value2,..) mt i tng xu c th
nhn 0
hoc nhiu hn mi loi c th chn t danh sch cc gi tr
:value1,value2, .. Mt tp hp c ti a 64 thnh phn.
Gi tr null ngha l khng c d liu,n khc gi tr 0 v xu
rng.
Gi tr null c th c k hiu bi \n cho vic truy xut
file
dng text.
4 .Ct ch s.
Tt c cc kiu ct ca MySQL c th c ch s ho .Vic dng
ch s ho trn cc ct c lin quan vi nhau l cch tt nht
ci tin vic thc hin ca cu lnh Select.
Mt bng c th c ti 16 ct ch s, di ch s ti a l
256
bytes ,mc d c th thay i khi bin dch MySQL.
i vi ct kiu char v varchar bn c th ch s ho phn
u
ca ct.Nh vy s nhanh hn v cn t khng gian a hn l ch
s
ho trong c ct.C php dng trong mnh CREATE TABLE
nh
sau:
KEY index_name(colname(length)).
V d sau s to mt ch s ho cho 10 k t u ca ct
tn:
MySQL>CREATE TABLE test(
Name char(200)not NULL
KEY index_name(name(10)))
i vi ct kiu BLOB v TEXT, bn phi ch s ho mt phn
u ca ct, khng th ch s ho c ct c.
To ch s trn nhiu ct.
MySQL c th to ch s trn nhiu ct. Mt vic ch s ho
c th ln ti 15 ct(trn ct char v varchar bn c th ch s ho
phn u ca ct nh mt phn ca vic ch s ho).
Vic ch s ho nhiu ct c xem nh mt mng c
sp xp m cha cc gi tr c to bi vic kt ni cc gi tr
gia cc ct c ch s ho .

Mysql s dng ch s ho nhiu ct nh l cch truy


vn
nhanh hn khi bn xc nh c s lng ln thng tin
ca
ct
u tin ca sp xp trong mt cu lnh WHERE, thm ch
nu bn

73

khng xc nh gi tr i vi cc ct khc th thng tin ly


c vn chnh xc .
V d :
Mysql> CREATE TABLE test(
Id int NOT NULL,
Last_name char(30)NOT NULL,
First_name char(30)NOT NULL,
PRIMARY KEY(id),
INDEX name(Last_name, First_name);
Khi tn s c ch s thng qua 2 ct Last_name, First_name.
Vic ch s s c p dng cho vic truy vn n cc gi tr c
th trong phm vi ca ct last_name hoc c Last_name v
First_name. Do , ct tn s c dng trong truy vn di y:
Mysql>SELECT* FROM test WHERE
last_name=Lan;
Mysql>SELECT* FROM test WHERE
last_name=Lan
AND first_name=Nguyn;
Mysql>SELECT* FROM test WHERE
last_name=Lan
AND(first_name=Nguyn)OR(first_name=L)
Mysql>SELECT* FROM test WHERE last_name=Lan;
AND(first_name>=L)AND(first_name<=M)
Tuy nhin ct tn s khng c dng trong truy vn di y :
Mysql>SELECT* from test WHERE last_name=Lan
Mysql>SELECT* from test WHERE
last_name=Lan
OR(first_name=Nguyn)
S dng cc kiu ct t nhng b my CSDL khc
y l cch to ra mt cch d dng c s dng m SQL
cho
cc h qun tr CSDL khc c c s l SQL.y chnh l nh x
kiu
t CSDL khc sang kiu tng ng bn MySQL,do d dng
chuyn bng t CSDL khc sang bng c kiu trong MySQL .

74

Kiu cc thnh phn khc


Binary(num)
Char varyfing(num)
Float4
Float8
Int1
Int2
Int3
Int4
Int8
Long
Long

Kiu trong mySQL


Char(num)binary
Varchar(num)
Float
double
Tinyint
Smallint
Mediumint
Int
Bigint
Varbinaryint mediumBlob
Varchar mediumText

Midleint
Varbinary

Mediumint
Varchar(num)Bynary

Nu bn to bng vi kiu s dng l ca b my CSDL khc th


khi a ra lnh :DISCRIBE tbl_name,khi Mysql s ghi li cu
trc bng ny vi kiu tng ng trong Mysql.
5.Cc kiu bng trong MySQL
Trong Mysql c 4 kiu bng khc nhau ,c th to nhiu kiu bng
vi cu lnh
CREATE TABLE:
Kiu bng MyISAM(indexsequential acces method):y l
kiu bng mc nh c to ra khi bn dng lnh Create,n l c
s
trong
m lnh ISAM v c mt s s m rng hu dng to ra file vi
phn
m rng .MYI
Kiu bng MyHeap:Cc bng kiu ny c lu tr trong b
nh ,vic ch s ho ca chng c thc hin bi hm bm,v vy
m tc thc hin ca bng kiu ny cc k nhanh,nhng n
phI tr gi rt t ,v d liu ca ta b mt .V vy bng ny ch
dng tm thi ,bn c th ch ra s hng ti a trong cu lnh Create
table .Kiu
bng ny c th chim gn ht b nh ca bn ,v vy khng th s
dng cc ct kiu blob,text hoc auto_increment.
Bng kiu BDB:Cc bng kiu ny l nhng giao dch an
ton ,chng c cung cp cc lnh COMMIT,ROOLBACK,cc
bng kiu ny hot ng chm hn cc bng c kiu MyISAM

75

Bng kiu Merge:y l kiu bng mi ,m lnh cho kiu


bng ny mi ang phin bn bta,tuy nhin n s nhanh chng
n nh ,y chnh l bng ISAM nhng chng ch c chn
la mt bng
,ch c insert,update,delete mt bng m bn chn ,nu bn
mun xo bng ch cn ch nh xo merge.Bng kiu ny gip x
l cc vn sau ,d qun l v tch ra thnh nhiu bng khc nhau
,nng cao tc x l ,vic tm kim s hiu qu hn.
II. Cc hm trong MySQL
Hm dng trong cu lnh SELECT v WHERE
1. Hm nhm.
Mysql>select 12*3
->7
Mysql>select (12)*3
->9
2. Cc php ton x l thng thng
Cng : Mysql>select 35
->8
Tr : Mysql>select 3-5
->-2
Nhn: Mysql>select 3*5
->15
Chia:Mysql>select 3/5
->0.6
Mysql>select 3/0
->NULL
3. Php ton thao tc vi bit
S bit ti a l 64 bits
Php AND
Mysql>select 29&15;
->13
Php OR:
Mysql>select 29\15;
->31
Dch trI:
Mysql>select
1<<2;
->4
Dch phi:

76

Mysql>select
4>>2;
->1
4. Php ton lgic
Cc php and(&),or(::),not(!).Cc gi tr tr v l 0 hoc 1 tng
ng ng hoc sai
V d:
Mysql>select not 1;
->0
5. Cc php so snh(>=,>,<=,<)
MySQL thc hin php so snh theo quy tc sau:
-Nu mt trong hai i s l NULL th kt qu so snh l
NULL,tr php tng ng .
-Nu c hai i s l kiu xu th c so snh nh gia cc
xu
vi
nhau .
-Nu c hai u l s nguyn th c so snh nh cc s nguyn.
-Gi tr hexa c xem nh l xu nh phn nu khng so snh
vi
s
khc .
-Nu mt trong nhng i s l kiu TIMESTAMP hoc DATETIME
cn i s kia l mt hng s th hng s s phI c chuyn
sang kiu TIMESTAMP trc khi so snh. chnh l lm cho vic
s dng ODBC thn thin hn.
-Trong tt c cc trng hp khc th i s c xem nh l s
thc.
V d:
Mysql>SELECT 1>6x;
->0
Mysql>SELECT 7>6x;
->1
Mysql>SELECT 1=x6;
->1
Mysql>SELECT 1 is NULL,0 IS NULL,NULL IS NULL
->0 0 1
php ton BETWEEN:
expr BETWEEN min AND max
Mysql>select 1BETWEEN 2 AND 3;
->0
Mysql>select bBETWEEN a AND
c;

->1
Mysql>select 2BETWEEN 2 AND x3;
->0
Php ton in,not in(value1,)
77

mysql>select 2 IN
(0,4,dfdg);
->0
mysql>select dfdg IN
(0,4,dfdg);
->1
Php ton ISNULL
mysql>select ISNULL(11);
->0
mysql>select ISNULL(1/0);
->1
6. Cc hm so snh xu
i vi cc hm so snh xu th c phn bit ch hoa ,ch thng
expr LIKE pat[ESCAPE escape-char]
gi tr tr v c th l s hoc xu,vi hm ny c th dng hai k
t i din l %,%: gi tr tr v c th l s cc k t
-: gi tr ph hp ch l mt k t
Tng t ta s c hm NOT LIKE:
NOT (expr LIKE
pat[ESCAPE escape-char])
V d : mysql>select h LIKE
h\-;
->1
mysql>select
10
LIKE
1%;
->1
Hm STRCMP(expr1,expr2):tr v 0 nu 2 xu nh nhau ,-1 nu
i s u nh hn i s hai theo th t sp xp ,ngoI ra th
bng 1
mysql>select STRCMP (text1,text2);
->-1
mysql>select
STRCMP
(text1,text);
->1
mysql>select
STRCMP
(text1,text1);
->0
Php ton cast
mysql>select a=A;
->1

mysql>select BINARY
a=A;
->0
Hm IF(expr1,expr2,expr3)

78

Tng ng vi hm if kp trong ngn ng C,nu expr1 ng


th hm nhn gi tr
expr2,ngc li th nhn gi tr
expr3
V d:
Mysql>select
IF(1<2,4,5);
->4
Mysql>select
IF(1>2,yes,no);
->no
gi tr tr v c th l kiu s hoc xu tu theo ng cnh ph hp .
7. Cc hm ton hc.
-ABS(x): gi tr tuyt i ca x
mysql>select ABS(-3);
->3
mysql>select ABS(3);
->3
-SIGN(X): Du ca biu thc trong ngoc ,tr li 0 nu X=0,-1
nu X<0;1 nu X>0
mysql>select (3-5);
->-1
mysql>select (0);
->0
mysql>select (3);
->1
-MOD(N,M):ly phn d ca php chia n cho
m
mysql>select MOD(30,6);
->0
mysql>select 13%6;
->1
-ROUND(X):Ly phn nguyn gn X nht
-exp(x),log(x),log10(x)
-POW(x,y):x m y
Tng t ta c cc hm ton hc khc nh:
sin(x),cos(x),tan(x),asin(x),acos(x),atan(x),rand();
8. Cc hm x l xu:
-Char(N,) hm tr v dy cc k t c m ACCSI c lit k
trong
ngoc

VD: mysql>select CHAR(77,121,83,81,76);


79

->MySQL
mysql> select
CHAR(77,77.3,77.3);
->MMM
-Hm ghp 2 xu :
CONCAT(str1,str2,)
vd : mysql> select
CONCAT(MY,S,QL);
->MYSQL
mysql>
select
CONCAT(MY,NULL,QL); ->NULL
mysql> select CONCAT(12.5);
->12.5
-CONCAT_WS(separator,str1,str2..)
mysql> select CONCAT_WS(,,first name,last
name); ->first name,last name
mysql>
select
CONCAT_WS(,,first
name,NULL,last name);
->first name,last
name -Cc hm v dI ca
xu :
LENGTH(str)
0CTET_LENGTH(str)
CHAR_LENGTH(str)
CHARACTER_LENGTH(str)
Mysql>select
LENGTH(text);
->4
mysql>select
0CTET_LENGTH(text) -Cc hm nh v
xu con
LOCATE(substr,str)
POSITION(substr IN str)
Mysql>select
LOCATE(nam,phngnam);
->7
Mysql>select
LOCATE(nama,phngnam);
->0
NgoI ra trong Mysql cn rt nhiu cc hm lin quan n
vic
x l xu khc nhng khng lit k y .Ta s sang
chng

mi

80

CHNG III.

CC LNH THAO TC VI CSDL

I. Cc lnh thao tc vi CSDL


1. Lnh to CSDL
C php :CREATE DATABASE[if not exists] db_name;
To ra CSDL nh l to mt th mc m trong c cc file,y
ch l to th mc ch cha c file,m cc file y l cc
bng.Vy ta s phi c cu lnh to bng
CREATE DATABASE IF NOT EXISTS NHANSU;
Cu lnh trn s to ra mt CSDL tn NHANSU,nhng cha c
bn no c to ra.
T kho if not exists nu c ch ra s trnh c mt li pht sinh
nu nh trn my c c s d liu ny ri.
2. Lnh xo CSDL.
C php:Drop Database [if esists]db_name.
Cu lnh ny s xo tt c cc bng trong c s d liu v xo lun c
c s d liu c tn l DB_NAME.
V d:Drop Database [if eists] NHANSU
Nu bn thc hin xo mt c s d liu vi kt ni c s d liu
th
c
CSDL ngun v kt ni s b xo.Bn phI rt cn thn i vi lnh
ny,n
s xo th mc vi tn ca CSDL v tt c cc file vi cc phn m
rng
nh
sau:
.BAK
.DAT
.HSH
.ISD
.ISM
.ISM
.MRG
.MYD
.MYI
.DR
.FRM
Trong cc phin bn 3.22 hoc c hn ta c th ch nh t
kho
if
esists ngn mt li xut hin nu nh CSDL cha c trn
a.
II. Cc lnh thao tc trn bng v x l i vi bng.
1. Lnh to bng.
C php:
CREAT{TEMPORARY}TABLE{IF NOT ESISTS}
Tbl_name [(creat_definition,)]
[table_options] [select_statement]

81

Lnh s to ra mt bng trong c s d liu hin ti nu c s d


liu cha tn ti th s c li pht sinh.Trong phin bn Mysql3.2.2
hoc mun hn tn bng c th c ch nh r l
db_name.table_name trong trng hp ny my s thc hin m
khng quan tm ti vic c s d liu c tn ti hay khng.
Trong :
Tbl_name l tn bng cn to
table_options :ch ra kiu ca bng cn to v nhng c tnh ca
bng cn to
table_options ={ISAM | MYISAM | HEAP | MERGE}
or AUTO_INCREMENT=#:Gi tr tip theo m bn mun t
cho
bng
or AUTO_ROW_LENGTH=#:Gi tr trung bnh dI ca
hng trong bng
or COMMENT=string:li bnh lun ti a 60 k t
or MAX_ROWS=# s hng ti a m bn nh lu
tr creat_definition:c nh ngha nh sau:
creat_definition:
col_name type
[NOT NULL | NULL] [DEFAULT
default_value]
{ AUTO_INCREMENT}
[PRIMARY KEY}{reference_definition]
or PRIMARY KEY (index_col_name,)
or KEY [index_name] (index_col_name,)
or INDEX [index_name] (index_col_name,)
or UNIQUE {INDEX} [index_name] (index_col_name,)
or FULLTEXT {INDEX} [index_name] (index_col_name,
) or {CONSTRANINT symbol] FOREIGN KEY
index_name ((index_col_name,)
[reference_defintion]
or CHECK (expr)
type:Kiu ca ct c to trong bng
REFERENCES tab_name [(index_col_name,)]
[MATCHFULL | MATCHPARTIAL]
[ON DELETE reference_option ]
[ON UPDATE reference_option]
reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION | SET
DEFAULT

82

Trong phin bn 3.23 bn c th s dng t kho temporary


khi to mt bng,bng tm ny s t ng c xo khi kt thc
mt
phin lm vic .
NOT NULL: Nu ct c ch nh l NOT NULL th khi nhp liu
ta bt buc phI nhp d liu cho ct ny .
NULL :i vi ct kiu timestamp s c s khc bit v gi tr
NULL
so vi nhng ct c nhng kiu khc,bn khng th a ra gi tr
NULL vi ct c kiu timestamp nu t l NULL th n s t
ng
t ngy gi hin ti,bi v ct c kiu stamp s dng cch thc
ny
nn thuc tnh NULL hoc NOT NULL s khng c t nh
nhng
ct thng thng v n s c l I nu bn ch nh Iu ny .
DEFAULT<gi tr ngm nh >:ct ny s t ng c t l gi
tr
ngm nh nu nh ta b qua khng nhp giv tr cho ct ny .Gi
tr
ngm nh phI l hng s theo ngha l ta khng th t gi tr mc
nh cho ct l gi tr tr v ca mt hm ,nu ct c khai bo
l
NOT NULL th gi tr ngm nh s ph thuc kiu ca ct
Nu khng t DEFAULT
-AUTO_INCREMENT:ch c i vi ct s nguyn ct ny s t
ng c tng khi nhp d liu .Nu bn xo mt hng cha
gi tr ln nht ca ct auto_increment th gi tr ny s dng li
cho ln nhp liu sau (Iu ny ch xy ra i vi bng loi ISAM
m khng xy i vi bng MYISAM)
ch :Mi hng ch c mt ct t l auto_increment v phI c
t l ch s
-UNIQUE KEY:y l kho ca bng n ch c th nhn mt gi tr
nht nh,s c li nu nh ta chn vo mt hng ca bng gi tr
kho trng vi kho ca hng tn ti .
-PRIMARY KEY:nh ngha kho chnh ca bng,l kho duy nht
vi rng buc rng tt c cc gi tr kho u phI t NOT
NULL mi bng ch c th c mt kho chnh.
-FOREIGN KEY :kho ngoi dng lm kho chnh ca bng khc
-Mnh SELECT :Nu c thm mnh SELECT sau cu lnh
CREATE TABLE th Mysql s to cc trng mi cho tt c cc
thnh phn nm trong cu lnh SELECT
V d ta to bng hosinh
CREATE TABLE HOCSINH(,

Mahs char(5) NOT NULL,PRIMARY KEY,


Hoten varchar(35),
Ngaysinh date,
Quequan varchar(40));

83

By gi ta to bng SINHVIEN gm c mt trng masv v


cc trng hoten,quequan,ngaysinh ly t bng HOCSINH:
CREATE TABLE SINHVIEN(,
Masv char(5) NOT NULL PRIMARY KEY,
SELECT hoten,ngaysinh,quequan from HOCSINH);
Mi bng tbl_name s c thay bi mt s file trong th mc
c s d liu ,nu kiu bng l MYISAM bn s thu c cc
file sau khi thc hin lnh to bng
Tn file
Chc nng
Tbl_name.frm
file nh dng bng
Tbl_name.Myd
file cha d liu
Tbl_name.MyI
file ch s
2. Lnh sa cu trc bng
C php :ALTER[IGNORE] TABLE tbl_name
alter_spec[,alter_spec...] alter_specification :
ADD[COLUMN] create_definition[FIRST |AFTER
colum_name]
Or ADD[COLUMN] (create_definition, create_definition,..)
Or ADD INDEX[index_name] (index_col_name,..)
Or ADD PRIMARY KEY(index_col_name,..)
Or ADD UNIQUE[index_name](index_col_name,..)
Or ADD FULLTEXT[index_name](index_col_name,..)
OR ADD[CONSTRAIN symbol] FOREIGN KEY index_name
(index_col_name)
[referent_definition]
or ALTER[COLUM] col_name{SET DEFAULT literal |DROP
DEFAULT}
OR CHANGE[COLUM] old_col_name
create_definition
Or MODIFY[COLUMN] create_definition
OR DROP[COLUMN] column_name
OR DROP PRIMARY KEY
OR DROP INDEX index_name
Or RENAME[TO] new_tbl_name
Or table_options
Lnh ALTER TABLE cho php bn sa cu trc ca mt bng
c,v d bn c th thm hoc xo ct,to hoc hu ch s,thay i
kiu ca ct c ,hoc i tn ct hoc i tn bng ,bn c th
thay i li ch thch cho bng hoc kiu ca bng .
Nu s dng lnh ALTER TABLE thay i mt ct
c
ch nh r nhng DESCRIPE tbl_name ch ra rng ct khng th
thay
i ,c ngha l Mysql b qua s thay i ny do mt l do no

.V
84

d nu bn c thay i mt ct c kiu varchar sang ct kiu char


th Mysql s khng thc hin vic thay i nu trong bng c cc
ct c di thay i .
Lnh ALTER TABLE thc hin vic to mt bn sao tm thi ca
bng ngun vic sa i thc hin trn bng sao ny ,bng
ngun s
c xo khi bng mi c i tn v hot ng theo cch
ny nn
vic cp nht s c thc hin mt cch t ng mt ln na
ti
bng mi
s dng lnh ALTER TABLE bn cn phi c
quyn :select,insert,update,create,drop i vi bng.
-Mt s v d dng lnh ALTER TABLE :
sa i tn mt ct :
ALTER TABLE hocsinh CHANGE hokhautt,hokhautt varchar
(40);
Nu bn mun thay i kiu ca ct m khng mun i tn th bn
vn phi vit tn ca ct 2 ln .
ALTER TABLE hocsinh CHANGE hokhautt,hokhautt CHAR
(40);
Ta cng c th dng MODIFY thay i kiu ca ct
ALTER TABLE hocsinh modify ngaysinh char(10);
Nu s dng lnh CHANGE hoc modify vi mt ct sp xp
m file ch s tn ti th bn khng th sp xp nhiu hn s
k t c ch s ho .
Khi dng change hoc modify Mysql s c gng chuyn d liu
sang kiu mi mt cch tt nht .
-drop index :hu file ch s nu ct c sp xp lgic (ch s ) m
ta xo n th n cng c xo thnh phn ch s ny cng s
c xo Drop primary key xo kho chnh
-ORDER BY:cho php to mt bng mi vi hng c ch ra
mnh order by ,ch rng bng s khng cn nh c trong
mnh
order sau khi chn v xo
i tn bng : ALTER TABLE old_name rename new_name;
chuyn mt ct t kiu integer sang tinyint not null(vi
cng
tn ) v i ct c tn l hoten char(10)->char(20) v i t
hoten>hovaten
ALTER TABLE sinhvien modify masv tinyint not null ,change
hoten hovaten char(20);
B sung thm trng ngaysinh
ALTER TABLE sinhvien add ngaysinh timestamp
; chuyn ct thnh kho chnh

ALTER TABLE sinhvien add primary key(masv);


85

3. Lnh i tn bng
C php :Rename table tbl_name |to newtbl_name
|,tbl_name2 to newtablename,]
Vic i tn thc hin mt cch t ng c ngha l trong khi
thc hin i tn s khng th truy nhp vo bng ny .
Vic i tn thc hin t tri qua phi ,v vy nu bn mun
chuyn i gia cc bng bn s thc hin nh sau :
RENAME TABLE old_table to backup_table,
New_table to old_table,
Backup_table to new_table;
Bn c th i tn bng gia 2 CSDL khc nhau :
RENAME TABLE curent_database.table_name to
otherdatabasse.table_name
Khi bn thc hin cu lnh rename bn khng th thc hin vic
kho bng hoc thc hin mt giao dch.
4. Lnh xa bng:
C php :Drop table [if esists ]
tbl_name1
[,tbl_nme2,...] [restrict/cascade]
Lnh ny c th xo mt bng hoc nhiu bng,tt c d liu
trong
bng s b xo.Lnh Drop table khng phil mt giao din an
ton.
5. Lnh ti u bng.
C php:
Optimize table tbl_name [,tbl_name,]
Lnh ny nn dngkhi bn xo phn ln d liu ca bng hoc bn
thc hin nhiu s thay i n bng nh thay i dI ca cc
hng(i vi bng c kiu varchar,bolb),hoc xo bn ghi
c
duy tr trong mt danh sch lin kt v cu lnh insert sau
dng li v tr ca bn ghi va xo.
Lnh ny ch thc hin vi bng kiu MYISAM v BOB.
6. Lnh Check table (Kiu tra bng)
C php:
Check
table tbl_name
[tbl_name,]
[option];
Option=Quick/fast/medium/extend/change
d

Cu lnh trn ch thc hin i vi bng MYISAM nu khng ch


nh
option n s mc nh l medium.Cu lnh thc hin vic kim tra
li
ca bng.

86

7. Lnh to bng sao lu(d tr)


C php:Backup table tbl_name [,tbl_name]
to path/to/backup/directory;
N s thc hin vic sao chp ton b cc file ca bng ti th
mc lu tr,kch thc lu tr l nh nht.
8. Lnh phc hi bng Backup.
C php:Restore table tbl_name,]
From/path/to/backup/directory
Phc hi mt bng c sao lu ch thc hin i vi bng
c backup bng tn ti s khng b ghi , bn s gp kh li
nu c phc hi mt bng tn ti.
9. Lnh phn tch bng.
C php:analiyze table tbl_name [,tbl_name ]
Phn tch v lu thuc tnh kho cho bng trong khi phn tch
bng s b kha vi kho read lnh trn ch thc hin i vi bng
MYISAM,BOB.MYSQL s dng vic sao lu cc thuc tnh kho
quyt nh trnh t vic kt ni gia cc bng khi thc hin
vic kt ni vi mt rng buc no .
10. Lnh repair table.
C php:REPAIR TABLE tbl_name1 [,tbl_name2,
]
[Quick] [extended]
Lnh trn ch thc hin i vi bng MYISAM,cu lnh ny
tng t i vi vic chy myisamchk_ r table_name;
Lnh thc hin sa cha bng b hng.
11. Lnh Delete.
Delete
[low_priority]
from
tbl_name [where <Iu kin>]
[limit rows] //gii hn s hng cn xo.
Thc hin vic xo cc bn ghi t tbl_name m n tho mn Iu
kin rng buc ca mnh where v tr li s hng b xo.
Nu khng c mnh where th tt c cc hng s b xo nu
mun
bit s bn ghi b xo bn s thc hin theo lnh sau:DELETE FROM
tbl_name WHERE1>0;
12. Lnh Truncate.
C php: Truncate table tbl_name ;

87

Cu lnh trn tng t nh lnh delete from


tbl_name; Nhng n cng c mt s khc bit:
-N s xo bng v to li bng mi vi cu trc ca bng
b xo,v vy n s thc hin nhanh hn l xo nhiu hng.
-N khng phI l mt giao dch an ton:n s t ng kt
thc
giao dch hin thi nu lnh commit c gi.
-Khng tr li s dng b xo.
13. Lnh Select.
C php:
SELECT{STRAIGHT_JOIN}{SQL_SMALL_RESULT}
{SQL_BIG_RESULT}
{SQL_BUFFER_RESULT}
{HIGH_PRIORITY}
{DISTINCT | DISTINCTROW |ALL}
Select_expression,...
[INTO
{OUTFILE
|
DUMPFILE}file_nameexport_options]
[FROM
table_references
[WHERE where_definition]
[GROUP BY {unsigned_integer |col_name |
formula}] [HAVING where_definition ]
[ORDER BY {unsigned_integer |col_name | formula}
[ASC |DESC],..]
[LIMIT{ofset,}rows]
[PROCEDURE procedure_name]]
y l lnh dng ly d liu t cc hng ca mt hoc nhiu
bng d liu.y l cu lnh thao tc chnh ca ngn ng SQL
Mt s v d v cu lnh MySql
CREATE TABLE persons(
Id SMALLINT UNSIGNED NOT NULL
AUTO_INCREMENT,
Name char(60) NOT NULL,
PRIMARY KEY (id));
CREATE TABLE shirts(
Id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
Style ENUM(t_shirt,polo,dress) NOT NULL,
Color ENUM (red,blue,orange,white,black) NOT NULL,
Owner SMALLINT UNSIGNED NOT NULL REFERENCES persons,
PRIMARY KEY (id));
INSERT INTO persons VALUES (NULL,antonio Paz);
88

INSERT INTO shirts VALUES


(NULL,polo,blue,LAST_INSERT_ID()),
(NULL,dress,whiteLAST_INSERT_ID()),
(NULL,t_shirt,blueLAST_INSERT_ID());
INSERT INTO persons VALUES(NULL,Lilliana Angelovska);
INSERT INTO shirts VALUES
(NULL,dress,orange,LAST_INSERT_ID()),
(NULL,polo,redLAST_INSERT_ID()),
(NULL,dress,blueLAST_INSERT_ID());
(NULL,t_shirt,white,LAST_INSERT_ID());
SELECT * FROM persons;
Id Name
1 Antonio Paz
2 Lilliana Angelovska
SELECT * FROM shirt;
id
1
2
3
4
5
6
7

style color Owner


Polo
Blue
1
Dress White
1
T_shirt Blue
1
Dress Orange 2
Polo
Red
2
Dress Blue
2
T_shirt white
2

SELECT s.* from persons p,shirts s


WHERE p.name LIKE LILIANA%
AND s.owner=p.id
AND s.color<>white;
Id
4
5
6

style color Owner


Dress Orange 2
Polo
Red
2
dress blue
2

14. Cc cu lnh cp nht d liu


a. Chn dng mi vo bng
Cu lnh Insert :
89

INSERT [LOW_PRIORITY / DELAYED / IGNORE]


[INTO] tbl_name [(col_name,.. .)]
VALUES (gi tr ct,.. .), (... ),.. .
hoc :
INSERT [LOW_PRIORITY / DELAYED / IGNORE]
[INTO] tbl_name [(col_name,.. .)]
SELECT.. .
hoc :
INSERT [LOW_PRIORITY / DELAYED / IGNORE]
[INTO] tbl_name
SET col_name_1=gi tr ct 1, col_name_2=gi tr ct 2,..
. Trong :
+Nu s dng thnh phn LOW_PRIORITY cu lnh ch c th
insert d liu khi khng c ai c d liu t bng ny, v ngi s
dng phi i khi cu lnh kt thc .
+Nu s dng thnh phn DELAYED ngi s dng s khng phi
i
cho ti khi cu lnh insert kt thc m vic thm dng mi vn i khi
khng c ai c d liu t bng ny. Thnh phn ny cn cho php thc
hin
cu lnh theo tng khi (thc hin nhiu cu lnh insert cng lc).
+Thnh phn IGNORE s b qua cc li khi thm dng mi vo
bng.
Trng hp li thng xy ra khi trng d liu l kho, dng mi s
khng
c thm vo bng .
V d :
INSERT INTO author (id, fullname, email)
VALUES (j001,John Writer,jw@somewhere.nice.com);
hoc :
INSERT INTO author SET
id=j001,fullname=JohnWriter,email=jw@somewhere.nice
.com;
hoc :
INSERT INTO tempauthor (id, fullname,
email) SELECT id, fullname, email FROM
author
WHERE id >= 100 ;
b. Cu lnh Replace

C php :

90

REPLACE [LOW_PRIORITY / DELAYED]


[INTO] tbl_name [(col_name,.. .)]
VALUES (gi_tr_ct,.. .)
hoc :
REPLACE [LOW_PRIORITY / DELAYED]
[INTO] tbl_name [(col_name,.. .)]
SELECT.. .
hoc :
REPLACE [LOW_PRIORITY / DELAYED]
[INTO] tbl_name
SET col_name1=gi_tr_ct1, col_name2=gi_tr_ct2,.. .
Cu lnh ny khng ging vi cu lnh INSERT , n thc hin
nh
sau:
+Mt dng (bng ghi) mi c to ra nu ct kho khng
b trng hoc bng khng c ct kha.
+Nu trng ct kho ton b d liu khng phi l kho c trong
danh sch ct s c thay bng gi tr tng ng.
+Nu ton b d liu cn thay i m b trng mt dng (bng ghi)
th d liu s khng c thm vo.

c. Cu lnh Update
Cu lnh thay th mt hoc nhiu ct ca mt dng (bng ghi) tho
mn iu kin no .
C php :
UPDATE [LOW_PRIORITY] tbl_name SET col_name1=ga_tr1,
col_name2,.. .
[WHERE biu_thc_iu_kin] [LIMIT #]
+Cu lnh ny lm thay i gi tr ct ca mt dng (bng ghi)
nu
tho mn iu kin ch ra trong mnh WHERE.
+Nu khng c mnh WHERE ton b cc dng s b thay
i .
+Chng ta c th gii hn dng (bng ghi) b thay i bng tu
chn
LIMIT.
V d :
UPDATE document SET title=Table of contents,

91

comment=Fixed typo in the title WHERE id=321;


Cu lnh trn cp nht li trng title v comment trong
bng document vi m id = 321.
III. Cc Thao tc tn bng
1. La chn cc hng
Bn c th chn cc hng ring bit t bng ca mnh.Nu bn
mun
kim tra li s thay i m bn thc hin vi ngy sinh ca
browser ,chn bn ghi browser nh sau :
Mysql>SELECT*FROM pet WHERE name=browser
Kt qu xc nhn rng nm c ghi ng by gi l nm
1989 m
khng phi l nm 1998
Cc xu s dng rt phong ph .Do bn c th s dng
tn l
browser hay BROWSER thi kt qu khng thay i.
Bn c th nh r gii hn trn bt k ct no (khc ct
tn) .V d
nu bn mun bit c nhng loi ng vt no sinh sau nm
1998 ta
s kim tra ct ngy sinh:
Mysql>SELECT * FROM pet WHERE both>=1998-1-1;
Bn c th kt hp cc k xc nh nhng con ch ci
Mysql> SELECT * FROM pet WHERE species=dog
AND sex=f;
Ta co th dng cc ton t AND hoc OR kt hp cc
k
Mysql> SELECT * FROM pet WHERE species=snake
OR
sex=bird;
AND v OR c th c trn ln nhau ,nu thc hin iu
tt hn ht hy s dng du ngoc n.
Msql> SELECT * FROM pet WHERE (species = "cat" AND sex =
m> OR
(species = "dog" AND sex = "f");
2. La chn cc ct:
Nu bn khng mun xem ton b bng m ch xem nhng
ct m
bn ang quan tm
.V d nu bn mun bit cc con vt ca mnh c sinh khi
no ,hy chn cc ct tn v ngy sinh:
Msql> SELECT name, birth FROM pet;
tm ra ai s hu nhng con vt ,s dng cu lnh sau:

Mysql> SELECT owner FROM pet;

92

Tuy nhin ,ch rng cu lnh chng qua l ly li trng


ngi s hu t mi bn ghi,v mt vi trong s chng xut
hin nhiu hn mt ln. cc gi tr khng b lp li ta thm
t kho DISTINCT:
Mysql> SELECT DISTINCT owner FROM pet;
Bn c th s dng diu kin WHERE la cjn cc dng cng
vi
cc ct.V d xem ngy sinh ca ch v mo thi th ta lm
nh
sau:
Msql> SELECT name, species, birth FROM pet
->WHERE species = "dog" OR species = "cat";
3. Phn loi cc hng
C th bn ch ti cc v d trc y v thy cc hng
kt qu
c hin th khng theo mt th t c bit no .tuy nhin
thng
d dng hn khi kim tra kt qu khi hng c phn loi
theo
mt cch c ngha . phn loi mt kt qu ta s dng mnh

ORDER BY sau y l v d v ngy sinh ca cc con vt c
phn loi theo ngy:
Mysql> SELECT name, birth FROM pet ORDER BY birth;
phn loi theo th t ngc li ,ta thm t kho DESC Vo tn
ct m bn ang phn loi :
Mysql> SELECT name, birth FROM pet ORDER BY birth
DESC;
Bn c th sp xp trn nhiu ct khc nhau .V d sp xp
theo
kiu vt sau l ngy sinh m khng quan tm n kiu con
vt
ng thi cc con vt tr nht xp u tin ,ta s dng cu lnh
sau;
mysql> SELECT name, species, birth FROM pet ORDER BY
species, birth DESC;
Ch rng t kho DESC ch p dng vi tn ct ngay trc
n
4. Xc nh ngy thng ,nm cho cc kt qu tnh ton:
MySQL cung cp mt rt nhiu chc nng m bn c th s dng

thc hin cc kt qu tnh ton theo ngy.Vi d tnh ton tui


hoc trch dn mt phn ca ngy. xc nh mi con vt ca bn

l bao nhiu tui ,tnh ton tui nh l khong cch gia ngy
sinh
v ngy hin ti. iu c thc hin nh sau:
mysql>
SELECT
name,
(TO_DAYS(NOW())TO_DAYS(birth))/365
FROM pet;
93

Mc d cc cu lnh ang lm vic nhng c mt vi iu v n


vn c th ci tin .
u tin kt qu c th c xem d dng hn nu cc hng c
trnh by theo mt th t no
Th hai, tiu cho ct tui th khng c ngha lm. Vn th
nht c th c gii quyt bng cch thm vo t kho ODER
BY
sp xp kt qu theo tn . lin h vi tiu ca ct, cung
cp
mt tn cho ct vi mt nhn xut hin trong kt qu(c gi l
b
danh)
mysql>
SELECT
name,
(TO_DAYS(NOW())TO_DAYS(birth))/365 AS age
-> FROM pet ORDER BY name;
Nu mun sp xp kt qu theo tui hn l theo tn, ta chi vic
s
dng mt cu lnh ODER BY khc
mysql>
SELECT
name,
(TO_DAYS(NOW())TO_DAYS(birth))/365 AS
age
->FROM pet ORDER BY age;

Mt cu lnh c th c s dng xc nh tui th cho


nhng con vt cht. Bn xc nh cc con vt no c
kim
tra
c hay khng gi tr cht l NULL. Sau i vi cc con c
gi
tr non_NULL, tnh ton s khc nhau gia gi tr cht v
sinh.

mysql> SELECT name, birth, death,


(TO_DAYS(death)TO_DAYS(birth))/365 AS age
FROM pet WHERE death IS NOT NULL ORDER BY age;
name
birth
Death
age
Bowse
1989-08-31 1995-07-29 |5.91
Cu lnh s dng death is NOT NULL vn tt hn l
death=!=NULL bi v NULL l gi tr c bit. iu ny c
gii thch phn sau ,
Nu bn mun bit con vt no c ngy sinh vo thng sau ?vi kiu
tnh ton ny ,nm v ngy u khng c lin quan ,bn chng qua ch
mun trch phn thng trong ct ngy sinh.Msql cung cp rt nhiu chc

nng trch n phn ngy sinhnh AR(),MONTH(),DAY OF MONTH()


,MONTH() u l chc nng phc hp . y xem n lm vic ra sao
,chy mt cu lnh n gin hin th gi tr ca c ngy sinh v
thng sinh
94

mysql> SELECT name, birth, MONTH(birth)

FROM pet;
Name
Fluffy

birth
1993-02-04

MONTH(birth
2

Vic tm cc con vt c ngy sinh vo thng sau ht sc d dng


.Gi
s thng hin ti c thng t .Sau ,gi tr thng l 4 v bn
tm cc
con vt c sinh vo thng nm nh sau:
o mysql> SELECT name, birth FROM pet WHERE
MONTH(birth) = 5;
Tt nhin c mt rc ri nh nu thng hin ti l thng 12.Bn
khng
ch thm 1 vo s thng (12) v tm xem con vt no sinh vo
thng 13
,bi v khng c thng nh vy .Thay vo ,bn tm cc con vt
sinh
vo thng 1
Bn cng c th vit cu lnh m n lm vic khng quan tm ti
thng
hin ti l bao nhiu ,vi cch bn khng phi s dng 1 s
thng ring
bit no trong cu lnh DATE=A() cho php bn thm mt khong
thi
gian vo mt ngy c a ra .Nu bn thm 1 thng vo gi tr
ca
NULL() ,sau o trch phn thng vi MONTH(),kt qu to ra thng
m
chng ta tm ngy sinh trong
mysql> SELECT name, birth FROM pet
->WHERE MONTH(birth) =
MONTH(DATE_ADD(NOW(), INTERVAL 1
MONTH));
Mt cch khc hon thnh cng vic tng t l phi thm 1
vo
c thng sau thng hin ti (sau khi s dng chc nng module
MOD)
bc xung quanh gi tr thng ti 0 nu n hin ti l thng
12
mysql> SELECT name, birth FROM pet
WHERE MONTH(birth) = MOD(MONTH(NOW()), 12)

1; Ch rng MONTH quay vng l mt s gi thng 1 v thng


12 ,v
MOD quay vng l mt s gia 0 v 11.Do s thm phi theo
sau
MOD() nu khng chng ta s i t thng 11 n thng 1
5. Lm vic vi gi tr NULL
Gi tr NULL c th gy ngc nhin cho n khi bn lm
quen
vi n .Theo khi nim NULL c ngha lgi tr khng
choc gi tr khng c bit n v n c xem
xt
95

mt mc khc bit hn so vi gi tr khc . kim tra


NULL bn khng th s dng cc ton t so snh s hc
nh:=,>,<... t mnh gii thch iu ny bn hy th cu
lnh
sau
mysql> SELECT 1 = NULL, 1 != NULL, 1 < NULL, 1 > NULL;
1 = NULL
1 != NULL
1 < NULL
1 > NULL
NULL
NULL
NULL
NULL
R rng l bn khng c cc kt qu c ngha t cc s
i
chiu ny hy s dng
IS NULL v IS NOT NULL thay th.
mysql> SELECT 1 IS NULL, 1 IS NOT NULL;
1 IS NULL
1 IS NOT NULL
0
1
Trong Mysql ,0 c ngha l sai v 1 c ngha l ng
Cch s l c bit ny ca NULL l l do ti sao trong mc
trc vic xc nh con vt no cht bng vic s dng
death =NOT NULL thay v death!=NULL ,li cn thit nh vy
6. S ph hp v kiu
Mysql cung cp cc mu chun cho php thay th mt kiu
no :v d nh s dng_ ch mt k t n l no
% ch mt s k t no c th l khng c k t
no.Ch
rng trong mysql khng s dng du=hay!= m s dng
LIKE hoc NOT LIKE.

Vi d tm mt tn bt u bng k t b
mysql> SELECT * FROM pet WHERE name LIKE
"b%";
Name
Owner
species
sex
birth
Buffy
Harold
dog
F
1989-05-13
Bowser
Diane
dog
M
1989-08-31

"%fy";
"%w%";

tm tn kt thc bng fy:


mysql> SELECT * FROM pet WHERE name LIKE
tm tn c cha mt k t bng w:
mysql> SELECT * FROM pet WHERE name LIKE
Dng LIKE:
mysql> SELECT * FROM pet WHERE name LIKE
"_____";

96

Mt s cc quy tc khc:
.Mt lp k t:c bao bi [...],v d
[abc][1-9] .K hiu * ch k hiu trng
.S dng k hiu ^$ ch bt u hoc kt thc
s dng thi ta phI vit t kho REGEXP pha trc
Tm tn bt u vi k t b
mysql> SELECT * FROM pet WHERE name REGEXP
"^[bB]";
Tm tn kt thc bng fy,s dng $ :
mysql> SELECT * FROM pet WHERE name REGEXP

"[wW]";

"fy$";
Tm tn c cha k tws dng [wW] tm c k t
thng
v k t hoa:
mysql> SELECT * FROM pet WHERE name REGEXP

Tm tn c cha ng 5 k t s dng^v $ tm kim:


mysql> SELECT * FROM pet WHERE name REGEXP
"^.....$";
Bn cng c th thc hin nh sau:
mysql> SELECT * FROM pet WHERE name REGEXP
"^.{5}$";
7. m hng

Cc c s d liu thng c s dng tr li cu hi


mc thng xuyn ca mt s kiu d liu xut hin
trong
bng nh th noV d ,bn c th mun bit bn c bao
nhiu
con vt ,hoc mi ngi ch c bao nhiu con vt ,hoc bn
c
th thc hin rt nhiu kiu iu tra dn s cc con vt ca
mnh
m tng s con vt m bn c th tng t nh cu hi l
c bao nhiu hng trong bng v con vt khi mt bn
ghi
trn mt con vt ,chc nng COUNT() m s kt qu nonNULL,do cu lnh m con vt ca bn nh sau:
mysql> SELECT COUNT(*) FROM pet;
D dng hn ,bn c th gi tn ca nhng ngi ch s
hu
cc con vt.Bn c th s dng COUNT() nu bn mun tm
ra

mi ngi ch c bao con vt


mysql> SELECT owner, COUNT(*) FROM pet
GROUP BY owner;

97

Ch rng ,s dng GROUP BY tp hp li tt c cc bn


ghi ca mi ngi ch.Nu khng c n,tt c nhng ci m
thu dc ch l 1 bc in bo li
mysql> SELECT owner, COUNT(owner) FROM
pet;
ERROR 1140 at line 1: Mixing of GROUP columns
(MIN(),MAX(),COUNT()...)
with no GROUP columns is illegal if there is no
GROUP BY clause
COUNT() v GROUP BY rt c ch cho vic m t d liu
ca
bn theo nhng cch khc nhau.
V d sau y s ch ra nhng cch khc nhau thc hin
cc
iu tra dn s con vt
S con vt theo loi:
mysql> SELECT species, COUNT(*) FROM pet
GROUP BY species;
Species
COUNT(*)
Bird
2
cat
2
dog
3
hamster
1
snake
1

BY sex;

S con vt theo gii tnh:


mysql> SELECT sex, COUNT(*) FROM pet GROUP
(trong phn ny ,NULL m ch khng bit gii tnh)
Sex
COUNT(*)
NULL
4
F
1
M
1
S con vt theo c loi v gii tnh:
mysql> SELECT species, sex, COUNT(*) FROM pet GROUP

BY species, sex;

Bn khng cn thao tc trn ton b mt bng khi s dng


COUNT().V d cu lnh trc khi c thc hin ch trn ch v mo
,nh sau:
mysql> SELECT species, sex, COUNT(*) FROM pet
-> WHERE species = "dog" OR species = "cat"

98

-> GROUP BY species, sex;


Hoc nu bn mun bit s con vt theo gii tnh v ch vi nhng
con
bit gii tnh:
mysql> SELECT species, sex, COUNT(*) FROM pet
-> WHERE sex IS NOT NULL
-> GROUP BY species, sex;
III.

S dng nhiu hn mt bng

Bng v con vt ch gi thng k l bn c nhng con vt no .Nu


bn mun ghi cc thng tin khc v chng ,nh l cc s kin
trong
cuc sng ca chng nh vic n gp bc s th y ,hoc cc la
c sinh khi no ,bn cn mt bng khc ,vy bng ny nn cn
g
n cn cha tn con vt ,v vy bn c th bit mi s kin ni n
con vt no
Cn ngy sinh bn bit c s kin xy ra khi
no Cn mt trng m t s kin
Nu bn mun c th phn loi c cc s kin th vic c
mt trng kiu s kin rt hu ch

Khi nhng yu cu c a ra vic trnh by CREATE


TABLE cho bng co th nh sau:
mysql> CREATE TABLE event (name
VARCHAR(20), date DATE,
->type VARCHAR(15), remark VARCHAR(255));

Vi bng v con vt ,vic chn cc bn ghi cn tin hnh bng vic


thit lp cc vng lu tr thng tin.
Fluffy
1995-05-15
litter
4 kittens, 3 female, 1 male
Buffy
1993-06-23
litter
5 puppies, 2 female, 3 male
Buffy
1991-10-12
litter
3 puppies, 3 female
Chirpy
1995-05-15
vet
needed beak straightened
Slim
1998-08-28
vet
broken rib
Bowser
1998-12-09
kennel
Fang
1993-06-23
kennel
Fang
1998-12-09
birthday
Gave him a new chew toy
Claws
1998-08-28
birthday
Gave him a new flea collar

Chn cc bn ghi nh sau:


mysql> LOAD DATA LOCAL INFILE "event.txt"
INTO TABLE event;

99

Da trn nhng g m bn hc c t cc cu lnh chy bng


pet bn c th thc hin vic gi tn trn cc bn ghi trong
bng
event,nguyn tc vn khng thay i .Nhng khi bn thn bng
event
khng tr li cc cu hi m bn c th hi ?
Gi s bn mun tm tui ca mi con vt khi n c la .Bng
evevt ch ra iu xut hin khi no ,nhng tnh ton tui
ca con
m bn cn ngy sinh ca n .N c la tr trong bng pet,nn
bn
cn c hai bng cho cu lnh ny:
mysql> SELECT pet.name, (TO_DAYS(date) TO_DAYS(birth))/365 AS age, remark
-> FROM pet, event
->WHERE pet.name = event.name AND type = "litter";
C rt nhiu iu ng lu v cu lnh ny
Mnh FROM ghi vo danh sch c hai bng
khi cu lnh cn ly thng tin t c hai
Khi kt hp thng tin t cc bng khc nhau ,bn
cn nh r c bao nhiu bn ghi v mi bn ghi c th c
ni vi
cc bn ghi ca bn kia.iu rt d khi c hai bn ghi u c
cng s ct.Cu lnh s dngWHERE dng ni cc bn ghi
hai bng da trn gi tr tn
Khi tn ct xut hin c hai bng ,bn phi xc
nh v bn no bn tm n kiu m ch ct .iu ny c
thc hin bng vic quy chiu tn ca bng vi tn ca ct
Bn khng nht thit phi c hai bng khc nhau tin
hnh
lin kt .i khi vic t lin kt li r hu ch
,nu
bn mun
IV.

Kt ni v khng kt ni ti server

1. kt ni ti server bn thng cung cp cho My SQL


mt
username, v mt password. Nu server chy trn mt my
khc hn
l my bn ang login. Bn cng cn xc nh mt hostname
lin
lc vi ngi qun tr ca bn tm ra nhng kt ni m
bn s s
dng kt ni.

Khi bn bit chnh xc hostname,username,password


th kt ni nh sau :
shell> mysql -h host -u user -p
Enter password: *** **

bn c

100

2. Mt vi My SQL n nh cho php ngi s dng kt ni m khng


c
tn t user ti server ang chy localhost trong nhng trng
hp ny
bn c th kt ni ti server nh sau:
shell> mysql
Sau khi bn bn kt ni thnh cng bn c th kt thc
vic kt ni nh sau :
mysql> QUIT
Bn cng c th s dng Ctr-D.
VI. V d v cc lnh c bn
*Sau y l nhng v d v cch gii quyt vn cng vi mysql
* Mt vi v d s dng hng shop lu tr gi ca mi
mc cho mi thng nhn.Gi s rng mi thng
nhn c m tp hp gi cho mi mc .Sau l kho
cho mi bn ghi
Bn c th to ra mt bng nh sau:
CREATE TABLE shop (
article INT(4) UNSIGNED ZEROFILL DEFAULT '0000' NOT NULL,
dealer CHAR(20)
DEFAULT ''
NOT NULL,
price DOUBLE(16,2) DEFAULT '0.00' NOT NULL,
PRIMARY KEY(article, dealer));
INSERT INTO shop VALUES
(1,'A',3.45),(1,'B',3.99),(2,'A',10.99),(3,'B',1.45),
(3,'C',1.69), (3,'D',1.25),(4,'D',19.95);
*V d v d liu nh sau:
SELECT * FROM shop
article
Dealer
Price
0001
A
3.45
0001
B
3.99
0001
A
10.99
0002
G
1.45
0003
D
1.69
0004
F
1.25
19.95
1. Gi tr ln nht cho mi ct
S mc cao nht l bao nhiu:
SELECT MAX(article) AS article FROM shop
Article
4

101

2.Dng lu tr gi tr ln nht cha trong ct :


Tm s dealer v price ca cc article t
nht
SELECT article, dealer, price
FROM shop
WHERE price=(SELECT MAX(price) FROM shop)
(trong mysql khng c th tc la chn)
nn lm iu phi chia thnh hai bc
Tm gi cao nht t bng bng lnh SELECT
S dng gi tr ny hon thnh cc cu lnh tip theo
SELECT article, dealer, price
FROM shop
WHERE price=19.95
Mt cch lm khc l sp xp cc hng gim dn theo gi v ch
a ra hng u tin s dng LIMIT:
SELECT article, dealer, price
FROM shop
ORDER BY price DESC
LIMIT 1
3. Gi tr m ca ct:mi nhm:ch mt gi tr
* vi mi article ,tm dealer(s) sao cho gi l cao
nht * trong ANSI SQL n s lm cng vi th tc
nh sau
SELECT article, dealer, price
FROM shop s1
WHERE price=(SELECT MAX(s2.price)
FROM shop s2
WHERE
s1.article
=
s2.article) *Trong mysql tt nht l lm
tng bc
a.a ra danh sch gm 2 ct(article,maxpice)
b.Vi mi article chn nhng dng m c gi cao
nht *V d nh sau:
CREATE TEMPORARY TABLE tmp (
article INT(4) UNSIGNED ZEROFILL
DEFAULT '0000' NOT NULL,
price DOUBLE(16,2)
DEFAULT '0.00'
NOT NULL);
LOCK TABLES article read;

102

INSERT INTO tmp SELECT article, MAX(price)


FROM shop GROUP BY article;
SELECT article, dealer, price FROM shop, tmp
WHERE shop.article=tmp.article AND
shop.price=tmp.price;
UNLOCK TABLES;
DROP TABLE tmp;
*Nu bn khng s dng mt temporary table bn phi dng kho
tmp table *C th lm iu vi nhng cu lnh n l
*C th gi hm MAX-CONCAT
SELECT article,
SUBSTRING( MAX(
CONCAT(LPAD(price,6,'0'),dealer) ), 7) AS dealer,
0.00LEFT(
MAX(
CONCAT(LPAD(price,6,'0'),dealer) ), 6) AS
price FROM shop
GROUP BY article;
4. S dng kho ngoi
Bn khng cn kho ngoi ni hai bng
Ch nhng th trong mysql khng lm c CHECK chc chn
rng nhng kho bn s dng thc s tn ti trong bng lin quan v
n khng t ng xo cc dng t bng cng vi kho ngoi c nh
ngha.Nu bn s dng kho bnh thng n vn lm vic ti cng:
CREATE TABLE persons (
id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
name CHAR(60) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE shirts (
id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
style ENUM('t-shirt', 'polo', 'dress') NOT NULL,
color ENUM('red', 'blue', 'orange', 'white', 'black') NOT NULL,
owner SMALLINT UNSIGNED NOT NULL REFERENCES persons,
PRIMARY KEY (id)
);

103

INSERT INTO persons VALUES (NULL, 'Antonio Paz');


INSERT INTO shirts VALUES
(NULL, 'polo', 'blue', LAST_INSERT_ID()),
(NULL, 'dress', 'white', LAST_INSERT_ID()),
(NULL, 't-shirt', 'blue', LAST_INSERT_ID());
INSERT INTO persons VALUES (NULL, 'Lilliana Angelovska');
INSERT INTO shirts VALUES
(NULL, 'dress', 'orange', LAST_INSERT_ID()),
(NULL, 'polo', 'red', LAST_INSERT_ID()),
(NULL, 'dress', 'blue', LAST_INSERT_ID()),
(NULL, 't-shirt', 'white', LAST_INSERT_ID());
SELECT * FROM persons;
Id
Name
1
Antonio Paz
2
Lilliana Angelovska
SELECT * FROM shirts;
color
blue
white
blue
orange
red
blue
white

owner
1
1
1
2
2
2
2

SELECT s.* FROM persons p, shirts s


WHERE p.name LIKE 'Lilliana%'
AND s.owner = p.id
AND s.color <> 'white';
Id
style
color
4
Dress
orange
5
Polo
red
6
Dress
blue

owner
2
2
2

1
2
3
4
5
6
7

Id

style
Polo
Dress
t-shirt
Dress
Polo
Dress
t-shirt

104

Chng IV : H thng quyn truy nhp c S D


LIU
Trong MYSql
I. Gii thiu chung v vn an ton v bo mt ca h thng
Trong vic tho lun v vn an ton ca h thng chng ta dc bit
nhn
mnhvic cn thit ca vic bo v an ton cho my ch ( khng n
gin l my ch Mysql ) chng li s tn cng di mi hnh thc :
nghe
trm,
sa
i cu trc .
Mysql s dng danh sch iu khin truy nhp
( ALSC ) (ACCESS
CONTROL LIST) m bo an ton bo mt ca vic kt ni,cu truy
vn v cc thao tc khc m ngi s dng c gng thc hin cng tn
ti mt s s h tr m ho kt ni gia my ch Mysql v my khch
.
Khi dng Mysql chng ta cn ch cc iu sau y:
- khng cho php ngi s dng truy cp n bng Mysql (ngoi tr nhng
ngi dng root)
- hc h thng cc quyn truy xut ca Mysql cc cu lnh cp
pht
quuyn v hu quyn ca ngi s dngnhm mc ch ngn chn
vic
truy xut ti Mysql, khng nn cp pht quyn hn nhiu hn
mc cn
thit, khng nn cp quyn ti tt c cc my ch.
Bn cn kim tra nhng iu sau y:
- c gng thc hin Mysql-u root ,nu bn c th kt ni vi my
ch m
khng cn mt khu, bn c mt s vn ri , bt k mt
ngi
no cng c th kt ni vi my ch Mysql viy quyn truy
xut,
bn cn xem li cc ch th khi ci t Mysql, ch n vic t
mt
khu gc (root).
- S dng lnh show grant v kim tra ngi dng truy cp n d liu g,
thu hi bt quyn hn khng cn thit .
- Khng nn lu mt khu di dng vn bn thun tu trong c s
d liu,
v khi my ca bn b mt k khc truy nhp th nhng k truy
nhp c
th c y mt danh sch cc mt khu v s dng chng.

-Khng nn dng mt khu t in v c nhiu chng trnh c bit

ph mt khu ny .
- Hy dung filewall n s bo v ti thiu l 50% tt c cc kiu khai thc
khc nhau ca phn mn v vy hy t mysql bn cnh firewall
- Kim tra ngi dng c nhp d liu ng tin cy khng
- Khng nn truyn ti cc d liu cha c m ho trn mng v d liu
c th b chn li s dng .
- Hc cch s dng cc tin ch tepdump, string bo v
105

II. Lm th no Mysql tr nn an ton chng li bn ti phm


my
tnh
khi kt ni n c s d liu thng thng bn hay dng mt mt
khu,
tuy nhin vic m ho chng th khng htc s mnh v mt s
n
lc
tn cng ca nhng k ph hoi c th b c mt khu ca
bn
nu
nh nhng k ph hoi c th chng ng c vic lu thng
gia
my
ch v my khch, tt c cc thng tin truyn trn mng u c
th
b
ngi no chng ng li v s dng chng, nu bn lo lng v
iu
ny th bn c th s dng vic m ho kt ni dng tep/ip khi
kt
ni
gia my ch v my khch.
m bo an ton cho h thng bn cn thc hin nhng vic sau :
- S dng password cho tt c ngi dng v nu khng dng password
th
bt k ngi dng no cng c th truy nhp c s d liu
-Bn c th thay i password cho tt c ngi dng bng chch thay
i
kch bn Mysql_install_db trc khi thc hin mysql hoc sa
password
cho ngi dng root
- sell>mysql-u root mysql;
mysql>update user set password =password (ne
password);
where user =root;
mysql>flh privileges;
- Khng nn chy mysql nh ngi dng unix root iu ny rt
nguy him
v ngi c quyn i vi file c th to file tng t nh root,
ngn
chn iu ny th mysql thng khng chy mysql nh dng root
tr khi
c ch th trc tip l :
-user=root;
Nu t mt khu cho ngi dng unix root trong kch bn
ca mysql server th bn phi m bo rng n ch c th
c c bi ngi dng root.

- Kim tra ngi dng Unix rng mysql ch chy i vi ngi dng c
quyn read/write.
- Trong cc trm lm vic Unix khng nn chy Mysql nh ngi dng
root tr phi iu thc s cn thit .
- Khng nn gn quyn process cho tt c ngi dng .
- Khng nn gn quyn o vi file cho tt c ngi dng .
Mt s s chn la lin quan n vic an ton khi khi ng Mysql
-- secure : tr li s ip bi gethost by name() li gi h thng s kim
tra
m bo chc chn rng chng s tr li tn ca my ch, iu ny
s gy
kh khn cho nhng ai pha ra mt tn my ly a ch.

106

-- skip-grant-table : iu ny s lm cho h thng khng s dng h


thng
quuyn v tt c mi ngi u c y quyn hn truy nnhp
vo
c s d liu (bn c th s dng h thng quyn bng cch
thc hin
mysqladmin flush-privileges).
-- skip-name-resolve: s chn la ny s lm cho tt c cc gi tr
trong ct
host ca bng phn quyn u l a ch IP hoc l localhost.
-- skip-networking: khng cho php giao thc tep/ip c kt ni .
-- skip-show database: khi c lnh SHOW DATABASE s khng tr li
mt
gi tr no c .
-- safe-show-database: lnh SHOW DATABASE s ch tr li gi tr
i vi nhng ngi c quyn i vi lnh ny .
III. Tn ngi dng v mt khu trong mysql
C rt nhiu nt phn bit gia cc cch thc khc nhau m tn
ngi dng (user name ) v mt khu(pasword) c s dng trong
Mysql v cch thc chng c dng trong Windows v Unix.
User namec mysql s dng cho mc ch nhn dng hu ht my
khch Myssql mc nh l khi ng nhp vo h thng s dng
tn ngi dng Unix hin ti iu ny c mt iu khng hay.
chng trnh my khch cho php nhiu tn ngi dng khc nhau
c
ch
ra
vi
la
chn
-u
hoc
user iu ny s lm cho h thng tr nn khng an ton trong mi
trng hp tr khi tt c cc tn ngi dng u co password b v
bt k mt ngi no cng c th ni vi my ch s dng mt
tn no v h s thnh cng nu nh tn khng c password
.
- Tn ca ngi dng c th di 16 k t.
- Password trong Mysql khng c lin h i vi password trong Unix.
Khng c s lin h cn thit gia mt khu bn s dng nh
nhp
vo my tnh unixvowis mt khu bn dng ng nho vo
c
s
d
liu
Gi mt khu mt cch an ton
Mt diu khng hay nu nh mt khu ca bn b mt ngi khc pht
hin ra.Di y l nhng phng php m bn ch r mt khu ca
mnh v cc nh gi v cc nguy him cho tng phng php .
S dng -pyour_pass hoc -password=your_pass trn dng lnh, iu
ny th tin li nhng khng an ton v mt khu cu bn s r

rng i vi chng trnh trng thi lm vic ca h thng, v


mt
ngi dng khc c th thc hin mt lnh hin th.
S dng -p trong trng hp ny chng trnh my khch s yu
cu nhp mt khu t dng lnh
Sell>mysql-u user_name-p
107

Enter password :*** **


Vic nhp mt khu s an ton hn v n s khng b nhn thy bi
ngi
dng khc. Tuy nhin vic nhp mt khu kiu ny ch thch hp cho
nhng
chng trnh m bn chy theop li tng tc .Nu nh bn gi mt
kch
bn
ca my khch th s khng c c hi nhp mt khu t thit b u
cui
.
Bn cng c th dng phng php lu mt khu ca bn vo file
cu
hnh
(v d bn c th to ra mt danh sch cc mt khu trong phn
[client]
ca
file My.cnf trong Home Directory ca mnh nu theo cch ny file
khng
nn dng c th c ghi.
Bn c th lu mt khu trong bin mi trng MySQL_pwd nhng
trng hp ny thng t dng v n khng an ton.
IV. H thng quyn truy xut c cung cp bi MySQL
Thng tin v quyn truy xut ca ngi s dng c lu tr trong
cc bng User, D, Host, Table_Priv v bng Column_Priv trong c s d
liu MySQL, MySQL server s c nit dung ca cc bng khi khi
ng.
Bng sau y lit k cc quyn v tng ng vi cc ct lin quan n
quyn v ng cnh m cc quyn p dng.
Cc quyn
Ct
Ng cnh
Select
Select_Priv
Bng
Insert
Insert_Priv
Bng
Update
Update_Priv
Bng
Delete
Delete_Priv
Bng
Index
Index_Priv
Bng
Alter
Alter_Priv
Bng
Creat
Creat_Priv
CSDL, Bng, Ch s
Drop
Drop_Priv
CSDL hoc Bng
Grant
Grant_Priv
CSDL hoc Bng
References
References_Priv
CSDL hoc Bng
Reload
Reload_Priv
Qun tr my ch
Shutdown
Shutdown_Priv
Qun tr my ch
Process
Process_Priv
Qun tr my ch
file
file_Priv
Qun tr my ch
Quyn Select, Insert, Delete, Update cho php bn thc hin cc
thao
tc
i vi cc hng ca bng trong c s d liu.
Quyn Alter cho php bn s dng cu lnh Alter Table.

Quyn Creat, Drop cho php bn to mi mt CSDL, bng hoc


xo
CSDL bng tn ti, ch rng nu bn cp pht quyn Creat, Drop
cho
ngi s dng, th ngi dng c th xo CSDL m trong quyn
truy
nhp n MySQL c lu tr.
108

Quyn Grant cho php bn cp pht quyn cho nhng ngi


dng
khc
nhng quyn m bn c.
Quyn i vi file cho php c vi ghi i vi file trn server,
s dng
cc lnh LOAD DATA INFILE v SELECT.. INTO OUTFILE bt k
ngi dng no c gn quyn ny u c th c hoc hoc ghi
i vi
file m SQL c th c hoc ghi.
Nhng quyn cn li c phc v cho cng vic qun tr m chng
c
thc hin bi chng trnh MySQL Admin. Bng di y s ch
cho bn
nhng lnh m quyn qun tr cho php bn thc hin.
Quyn
Nhng lnh c th thc hin
Reload
Reload, refresh, flush_privileges, flush-hosts, flush-logs, flushtables
Shutdown Shutdown
Process
Processlist, kills
Lnh Reload s ch th cho my ch thc hin vic c li bng cc
phn quyn, lnh refresh np li tt c cc bng, m v ng tt
c cc file log. Lnh flush-privileges tng t nh lnh reload,
mt s lnh flush-* khc thc hin chc nng nh refresh, nhng c
gii hn hp hn lnh refresh, n s thch hp trong mt s trng hp,
v d ban ch cn Flush i vi log file th lnh flush-logs thch hp
hn lnh refresh.
Lnh Shutdown s lm cho my ch ngng hot ng.
Processlist s hin th nhng thng tin trong sut qu trnh
hot
ng
vi my ch.
Lnh kills s tt mt phin lm vic vi my ch, bn c th
thc hin
2 lnh trn nhiu ln trong mt dng lm vic nhng bn
phi c
quyn Process.
Mt kin hay tng qut trong vic gn quyn cho ngi dng l
ch gn nhng quyn cn thit cho ngi dng m h cn h
thc hin nhng cng vic ca mnh.
Mt s ch i vi c im thc hin nhng quyn sau:
Quyn Grant cho php ngi dng cp nhng m h c cho
ngi
dng khc. Hai ngi s dng c cc quyn khc nhau, vi
quyn
Grant h c th kt hp nhng quyn ny.
Quyn Alter c th c s dng ph v nhng quyn

bng
vic
i tn bng.
Quyn i vi file c th b lm dng c mt s file trn
my ch
vo bng trong c s d liu, ni dung ca bng ny c th
b truy
nhp bng cch s dng nhng cu lnh Select, iu ny cng c
th
c thc hin i vi mt s c s d liu chnh ca my ch.

109

Quyn Shutdown c th lm dng t chi mt s dch v


i
vi
ngi s dng khc bng cch tt my ch.
Quyn process c th c s dng xem dng vn bn thun
Text
ca nhng cu truy vn hin thi k c nhng cu truy vn
t li
mt khu
Quyn i vi nhng c s d liu mysql c th b s dng
thay
i
password v mt s quyn truy nhp thng tin khc,
Mt s vn m bn khng th thc hin i vi h thng quuyn
hn trong Mysql
Bn khng th ch ra mt cch r rng rng ngi s dng khng th
thc hin c, ngha l bn khng th xc nh mt ngi dng
ph hp v t chi vic kt ni .
Bn khng th ch r mt ngi dng c quyn to v xo cc bng
trong mt c s d liu, nhng khng c quyn to v xo chnh CSDL
.
V. H thng quyn hot ng nh th no
H thng quyn trong Mysql m bo mt cch chc chn rng

mi
ngi dng ch c thc hin nhng cng vic m h c cho php
thc
hin. khi bn kt ni vi my ch Mysql th nhng c tnh ca bn
s
c
xc nh bi my ch t chnh ni m bn kt ni v tn ngi dng
m
bn
nhp. h thng quyn s theo nhng c tnh ca bn v nhng g bn
mun
thc hin
Mysql xem xt c hostname v username c bn ch ra v mt
s
l
do n gin l tn cp cho ngi dng cung cp s thuc v ngi
mi
ni
trn mng. v d ngi dng c tn l Bill kt ni vo Whitehouse.gov
khng
cn thit phi ging ngoi dng Bill kt ni vo micrsoft.com.
Mysql
iu
khin iu ny bng cch cho php bn phn bit nhiu ngi
dng
trong
nhng my ch khc nhau m c cng tn ging nhau, bn c th
gn
cho

ngi dng c tn l Bill mt tp hp cc quyn kt ni


vo
Whitehouse.v mt tp hp cc quyn khc kt ni vo micrsoft.com
Mysql iu khin truy nhp bao gm hai khung cnh khc nhau
Khung cnh 1: my ch s kim tra bn c quyn kt ni hay khng
Khung cnh 2: khi bn kt ni vi my ch th Mysql s kim tra
nhng yu cu m bn a ra xem bn c quyn hn thc
hin n mt cch thch ng. v d nu bn kt ni vo CSDL v c
gng thc hin mt lnh Select hoc xo mt bng ca CSDL th
Mysql s kim tra xem bn c quyn select hoc drop thc hin
iu hay khng .
Mysql dng cc bng USER,DB,HOST trong CSDL mysql iu
khin truy nhp c 2 khung cnh trn, cc trng trong cc bng
ny c cung cp di y:
110

Tn bng
Cc trng phm vi

USER
Host
User
Password
Cc trng ch quyn Select_Priv
Insert_Priv
Update_Priv
Delete_Priv
Index_Priv
Alter_Priv
Creat_Priv
Drop_Priv
Grant_Priv
References_Priv
Reload_Priv
Shutdown_Priv
Process_Priv
file_Priv

DB

Host
Data
User
Select_Priv
Insert_Priv
Update_Priv
Delete_Priv
Index_Priv
Alter_Priv
Creat_Priv
Drop_Priv
Grant_Priv

HOST
Host
DB
Select_Priv
Insert_Priv
Update_Priv
Delete_Priv
Index_Priv
Alter_Priv
Creat_Priv
Drop_Priv
Grant_Priv

Mi bng phn quyn bao gm trng phm vi v trng quyn,


trng
phm vi xc nh cc phm vi cc mc trong bng cc khung cnh
l ni cc
m khp vo. v d trong bng ngi dung mc HOST ,USER c gi tr
L vnuh.vnn.vnv thu dng nhp ra s kt ni ti my ch bi
thukt
ni ti my ch vnuh.vnn.vntng t trong bng DB mc
HOST ,USER,
DB c cc gi tr l vnuh.vnn.vnv thu, repost dng nhn
ra s kt
ni bi thu kt ni ti my ch vnuh.vnn.vn, truy nhp n
CSDL repost bng table-priv,column-priv cha trng phm vi
ch ra cc bng, bng / ct c kt hp li cho cc mc c yu cu.
- thc hin chc nng kim tra truy nhp vic so snh gi tr ca Host
th
khng phn bit ch hoa ch thng, gi tr ca db, password v
table_name
th c phn bit ch hoa ch thng, column_name khng phn bit
ch
hoa
ch thng.
-Trng trong quyn mi bng ch ra cc quyn c gn bi cc
thc
th
bng l cc thao tc c th cho php thc hin. Trng phm vi

c
kiu
xu c khai bo nh trc y, gi tr mc nh cho mi
trng l rng.

111

Tn trng
Host
User
Password
Db
Table_name
Column_name

Kiu trng
CHAR(60)
CHAR(16)
CHAR(16)
CHAR(64)
CHAR(60)
CHAR(60)

Trong tt c cc bng uer, host, db tt c cc trng u khai


bo l Enum(N,Y), gi tr mc nh cho mi trng l N
-Trong cc bng table_priv, column_priv cc trng u c gn
kiu
tp
hp.
c im v quyn trong cc bng ca CSDL Mysql
-Bng user:
Trng phm vi trong bng user xc nh xem bn c c php
thc hin hoc khng c php thc hin kt ni bt k mt
quyn no c gn trong bng user th tt c cc quyn no l ton
cc trong mysql, ngha l cc quyn ny s c hiu lc i vi tt c CSDL
trn server
-Bng db v bng host c s dng kt hp vi nhau:
Trng phm vi trong bng db xc nh nhng ngi dng no
c php truy cp n CSDL no, my ch no, trng quyn s
ch ra cc thao tc no s c cho php thc hin.
Bng host c s dng nh mt s m rng ca bng db khi bn
mun
trao
cho cc thc th trong bng db c quyn i vi nhiu host. V d, bn
mun
mt ngi dng trong bng db c th s dng mt CSDL t nhiu
my
ch
khc nhau.
Bng table_priv, column_priv cng tng t nh bng db nhng n
c qun l mt cch chi tit hn, cc quyn s oc gn ti nhiu
mc khc nhau cho cc bng, ct trong CSDL.
Ch : Cc quyn phc v cho cng tc qun tr ch c ch ra trong
bng user bi v mt l do n gin l cc quyn ny ch thao tc vi
my ch nn khng c l do g a n vo trong bng phn quyn
khc.
VI. iu khin truy nhp
1. iu khin truy nhp
Khung cnh mt (Stage 1) thm tra kt ni thun hoc t chi vic
kt ni
ca bn da trn cc c tnh ca bn v thm tra li iu ny bng

cch bn
phi cung cp mt mt khu dng. Nu khng n s t chi vic kt ni
ca
bn, nu thnh cng n s chuyn sang khung cnh th hai (Stage 2).
Vic xc nh nhng c tnh ca bn da trn hai thng tin c bn:
112

- Tn my ch m bn mun kt ni
- Tn ngi dng
Vic kim tra s thc hin trn ba trng phm vi trong bng user l
host, user v password my ch chi chp nhn vic kt ni ca bn
khi m cc thc th trong bng user ph hp vi host, user v bn
phi cung cp password ng.
2. iu khin truy nhp
Khung cnh 2(Stage 2) xc minh yu cu khi vic kt ni ca bn
thnh cng mysql server s chuyn sang khung cnh 2, i vi mi
yu cu ca mi kt ni mysql server s thm tra xem bn c
quyn hn thc hin cc quyn hn hay khng da trn cc
loi thao tc m bn mun thc hin vic thm tra s oc thc hin
i vi cc trng quyn trong cc bng phn quyn, user, host, db.
Tt c cc quyn oc cp trong bng user s oc n nh l ton
cc cho tt c cc CSDL ni cch khc tt c cc quyn c cp trong
bng user l superuser.
V vy m bn ch nn cp quyn trong bng user cho nhng ngi
dng nh ngi qun tr my ch hoc ngi qun tr CSDL.
VII. Khi no vic thay i quyn hn c hiu lc
Khi mysql khi ng th ni dung ca tt c cc bng phn quyn
oc t vo b nh v khi n s c hiu lc.
Vic bn thay i tt c cc bng phn quyn s dng lnh
GRANT (Revoke) hoc t li mt khu s oc my ch ch ngay lp
tc.
Nu bn thc hin vic thay i cc bng phn quyn mt cch th
cng nh l s dng lnh INSERT, UPDATE, th bn nn dng lnh
flush priviliges hoc chy mysqladmin flush priviliges hoc
mysqladmin reload thng bo cho server bit reload cc
bng phn quyn.
Khi server thng bo mt ch rng cc bng phn quyn b thay
i th cc kt ni ang tn ti pha client s b thay i nh sau:
-Cc thay i i vi cc bng, ct s c hiu lc i vi cc yu
cu tip theo pha client.
-Cc thay i v quyn i vi CSDL s c hiu lc i vi cu
lnh userdb_name tip theo.
i vi cc quyn ton cc vic thay i password s c hiu lc
ln kt ni tip theo.

113

VIII. Ci t vic khi to h thng quyn trong mysql


-Sau khi ci t mysql bn c th t vic khi to cc quyn cho
mysql bng vic chy scripts/mysql_install_db. Kch bn ny s chy
mysqlserver khi cc quyn bao gm mt tp hp cc quyn
sau:
i vi ngi dng root s oc to nh mt superuser nn n c
th lm mi th, vic kt ni phi oc thc hin localhost.
Ch : Ban u vic khi to s khng yu cu mt khu i vi ngi
dng root v vy bt c ngi no cng c th kt ni nh mt ngi
dng root m khng b i hi password do vic u tim m bn
nn lm l thay i password cho ngi dng root.
- Bt c mt ngi dng no c to cng c th lm mi thc
i
vi
CSDL test nhng vic kt ni phi oc thc hin localhost.
IX. Gn thm quyn ngi dng i vi mysql
Bn c th to mt ngi dng mi bng hai cch: Dng lnh Grant
hoc thao tc trc tip trn CSDL mysql. Cch thc thng oc
dng hn c l dng lnh grant bi v n ngn gn v t li hn.
Cc v d sau s thc hin vic to mt ngi dng mi. thc hin
iu
ny th bn phi kt ni vi mysql nh mt ngi dng root v
ngi
dng
root ny phi c gn quyn insert i vi CSDL mysql v phi c
quyn
qun tr reload
Mysql> GRANT ALL PRIVILEGES ON *.* TO monty@localhost
IDENTIFIED BY some_pass WITH GRANT OPTION;
Mysql> GRANT ALL PRIVILEGES ON *.* TO monty@%
IDENTIFIED BY some_pass WITH GRANT OPTION;
Mysql> GRANT RELOAD, PROCESS ON *.* TO admin@localhost;
Mysql> GRANT USAGE ON *.* TO dummy@localhost;
Cc cu lnh trn gn quyn cho ban ngi dng monty, admin v
dummy. -ngi dng monty: y l ngi dng superuser vi y
cc quyn c
th kt ni bt c ni u nhng phi c password l some_pass.
-Ngi dng admin: ngi dng ny c quyn reload, process
nhng
phi ng nhp t localhost v khng yu cu password
- Ngi dng dummy c th kt ni m khng cn password nhng khng
oc gn quyn g c.
- Cng thc hin vic gn quyn nh trn theo cch khc ta c th lm nh
sau:

Mysql> INSERT INTO user


VALUES(localhost,monty,PASSWORD(some_pass),
Y, Y, Y, Y, Y, Y, Y, Y, Y, Y, Y, Y, Y, Y)
114

Mysql> INSERT INTO user


VALUES(%,monty,PASSWORD(some_pass),
Y, Y, Y, Y, Y, Y, Y, Y, Y, Y, Y, Y, Y,
Y) Mysql> INSERT INTO user SET Host=localhost,
User=admin, Reload_priv=Y, Process_priv=Y;
Mysql> INSERT INTO user (Host, User, Password)
VALUES(localhost,dummy,);
Mysql> FLUSH PRIVILEGES;

115