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

?

;i 14

5-

2013

004.45
32.973-018.2
62

Kevin Yank
& MySQL: Novice to Ninja, 5th. Edition Authorized Russian translation of the English edition
of PH P & MySQL: Novice to Ninja, 5th. Edition (ISBN 9780987153081) 2012 Sitepoint Pty. Ltd.
This translation is published and sold by permission of OReilly Media, Inc.,
which owns or controls all rights to publish and sell the same.

62

.
PHP MySQL. / .
.: , 2013. 384 . ( ).
ISBN 978-5-699-67363-6
,
. ,
, 20 ,
(CMS)
.
MySQL .
004.45
32.973-018.2

ISBN 978-5-699-67363-6

. , 2013
. 4 <, 2013

...................................................................................................................16

1. M yS Q L ............................................................................. 22
2. M ySQ L ...................................................................................... 41
3. ............................................................................................ 58
4. M ySQL ........................................ 87
5. ...........................................123
6. .............................................................. 137
7. ........................................................... 156
8.
........................................................ 194
9. , ............................................................. 211
10. M ySQ L....................................

252

11. SQ L- .....................................................................268
12. .........................................................................................281
. M ySQ L ............................................. 305
. M ySQ L.......................................... 328
. M ySQ L

................................................................. 348

. M ySQ L
............................................

.................................................. 366
374

............................................................................................................................... 15
S ite P o in t............................................................................................................................ 15
.................................................................................................................................16
...................................................................17
.......................................................................................................17
.................................................................................................19
S ite P o in t
..........................................................
19
- .......................................................................................19
S ite P o in t....................................................................20
...................................................................................................... 20
...........................................................20
1. M y S Q L ............................................................................. 22
-............................................................................ 23
W in d o w s.......................................................................................... 23
Mac OS X ........................................................................................ 30
L inux................................................................................................. 36
-...............................
36
- ..........................
37
.....................................40
2. M y S Q L ...................................................................................... 41
..................................................................................... 41
phpM yA dm in
SQ L -........................................................................ 42
............................................................... 47
..............................................
48
................................................................................................ 49
......................................................................... 52

.............................................................................. 54
.......................................................... 56
....................................................................... 56
......................................................... 57
3. ............................................................................................ 58
.................................................................... 59
, ................................
61
................................................................................................................... 62

.................................................................................................. 64
....................................................... 64
................................................ 70
73
............................................................
............................................................................................. 81
.........................81
....................
82
, ......................................................... 84
................................................................................... 86
4. M yS Q L ........................................ 87
...................................................
87
M y S Q L ................................... 88
M ySQ L .................................................... 91
-
..................................
93
............................................................................. 95
SQ L - ................................................. 100
S E L E C T .......................102
..................................................... 107
.........................................
115
...................................
121
5. .......................................... 123
123
..............................
............................................... 125
128
..........................................
...................................................................................................... 132
................................................................... 134
, ............................................................. 136

6. .............................................................. 137
137
...................................
H T M L - ....................................................................... 137
- ........................................................................... 139
...............................................................
...143
........................................................144
....................................146
.................................................151
155
.....................
7. ............................................................156
....................
156

..............
159
............................................................................. 161
......................................166
......................................................................170
............................................................................ 175
................................
176
....................................................182
........................................................................................... 192
............................................................................................. 193
8.
.........................................................194
.................................................................................... 195
................................ 200
..................................................................................... 201
204
.........................
.................................................................................................. 206
................................................................................ 208
...................................................... 210
9. , ............................................................. 211
........................................
211
.......................................................................................................216
................................................................................................ 225
............................................................................. 225
.......................................................................................... 228
.................................................................................. 233

............................................................ 240
: .................................................... 249
........................
251
10. M y S Q L .................................................................... 252
M y S Q L ......................................... 253

phpM yA dm in...........................................................................253

m ysqldum p ...............................................................................254

........................................ 255
M yS Q L .............................................. 258
, ............................................. 258
?............................................................................................260
............................
261
...................................................................................................265
, ............................................. 267
11. S Q L - .....................................................................268
S E L E C T ...................... 268
............................................................................................269
...............................................................................271
272
.......................
............................................................................274
....................................................................... 276
H A V IN G ................. 279
................................................. 280
12.

............................................................................ 281

........................................................................ 281
.......................................................................286
.............................................. 289
290
........................

....................................................................... 291
....................................................... 293
.......................................................................................296
.............................................. 302
M y S Q L ...............................
302
........................................ 303

........................ 303
......................................................................................................303
. M y S Q L ............................................. 305
W in d o w s.................................................................................................................305
M yS Q L .......................................................................................305
.............................................................................................306
Mac O S X ...............................................................................................................313
M yS Q L .......................................................................................313

......................................................................................316
L in u x ........................................................................................................................319
M yS Q L .......................................................................................320
.............................................................................................323
. M y S Q L .......................................... 328
A LTER T A B L E ....................................................................................................328
ANALYZE T A B L E .....................................................
331
B E G IN .....................................................................................................................331
C O M M IT ...............................................................................................................331
C R EA TE D A T A B A SE .......................................................................................331
C R EA TE IN D E X .................................................................................................331
C R EA TE T A B L E .................................................................................................332
D E L E T E .................................................................................................................334
D E S C R IB E /D E S C .............................................................................................334
335
D R O P D A T A B A SE .................
D R O P IN D E X ......................................................................................................335
D R O P T A B L E ...............................................................................................
335
E X P L A IN ...............................................................................................................335
G R A N T ...................................................................................................................336
IN S E R T ..........................................................................
336
LO A D DATA IN F IL E ........................................................................................337
O P T IM IZ E T A B L E ............................................................................................338
R EN A M E T A B L E ...............................................................................................338
R E P L A C E ..............................................................................................................338
R E V O K E ................................................................................................................339
R O L L B A C K ........................................................................................
339
S E L E C T ..................................................................................................................339
.................................................................................................342
U N IO N ...............
344
S E T ...........................................................................................................................344

10

SH O W
.......................................................................................................345
STA RT T R A N S A C T IO N ...................
346
.................................................................................
346
TRUNCATE
U P D A T E ................................................................................................................346
U S E ..........................................................................................................................347
. M ySQ L .............................................................................348
.............................................. 348
...............................................................................349
..........................................................................................352
.................................................................................356
..................................................................................................361
, G R O U P B Y .............................. 364
. M ySQ L ............................................................... 366
....................................................................................................367
..................................................................................................369
.........................................................................372
..........................................................................

374


(Kevin Yank) 15 .
, , ,
.
, 2001 SitePoint
. Build your own database
driven web site using P H P & MySQL (
MySQL).
. , .
, (Simply JavaScript Everything you
know about CSS is wrong!), SitePoint
Tech Times SitePoint Podcast.
learnable.com,
- JavaScript, MySQL, H TM L
CSS, -
Learnable.
Avalanche Technology Group,

.
() , ,
.
, -
.

SitePoint
SitePoint
, -.
http://www.sitepoint.com/1,
, ,
.

1 .
,
. . .

MySQL , .
2001 ,
,
H TM L- .
:
, . MySQL
,
,
.
MySQL ,
. .
, , W ordPress
( http://wordpress.com/), ,
,
.
, , -
, ,
-. ,
, , W ordPress
MySQL. ?

, MySQL .

2001 , MySQL
.
, .
. ,

. M ySQL
, . ,
,

. 2001

.
, MySQL .
: ,
. , ,

16

, .
MySQL . :
Windows, Mac OS X Linux.
,
MySQL. , !


-,
.
, H TM L-,
. CSS (Cascading Style Sheets )
JavaScript , , ,
, .
,
, . ,
SQL.
, .

,
MySQL. , ,
.


12 .
.
, .
,
, . 1
,
MySQL.
Windows, Linux Mac OS X,
, -.
2
MySQL .
,
. ,
.
3 .
. -,
.
,
. ,

17

,
.
4 , ,
MySQL,
.
,
.
-,
MySQL .
, ,
, ,
. -
-
. 5
,
. , ,
.

, .
. 6 ,
.
,
. ,

.
7 -,

. ,
.
: ,
,
, HTML.
8 ,
,
, .

?
-?
9. ,
,
, -
.
MySQL
. ,
, . 10

18

. ,
MySQL, , ,
,
.
, 5

MySQL. , ,
SQL. 11
,
.
-, ,
.
- .
, :
( ) . 12
, ,
. ,
,
MySQL.


MySQL . , ,
,
. , SitePoint
P H P -, , .
SitePoint ,
.

SitePoint
SitePoint ( http://www.sitepoint.com/forums/)
, -,
. : - ,
- , . ,
, .
- .
- ,
.
SitePoint : ( http://www.sitepoint.com/forums/
forumdisplay.php?34-PHP) M ySQL ( http://www.sitepoint.com/forums/
forumdisplay.php?88-Databases-amp-MySQL).

-
-, , http://www.sitepoint.com/
books/phpmysq!5/ .

19

.
. ,
, . ,
http://www.sitepoint.com/books/phpmysql5/code.php.
. .
.

.

SitePoint
, , ,
SitePoint : SitePoint,
PH PM aster, CloudSpring, RubySource, DesignFestival BuildMobile.
,
, , , -.
http://www.sitepoint.com/newsletter/.


SitePoint
- ,
books@sitepoint.com. .
,
.
.


,
.
.
<1> </>
<> . ,
.</>

,
. , ex am p le .c s s .
, .
, ,
.
function animate() {
new_variable = "";

20

.
function animate() {
return new_variable;

}
/
:

;
, ;
, ;
;

, ,
.

1
MySQL

, -
, HTML,
CSS JavaScript. , ,
,
, .
,
:
. , ? :
. , MySQL!
H TM L CSS , ,
JavaScript, , , , ,
, .
, -
.
, , -,
, (In te rn e t Explorer, Google
Chrome, Safari Firefox). - Apache H T T P
Server (Apache) In tern et Inform ation Services (IIS ). ,
.
,
.
,
P H P -. ,
, -
.
P H P -, .
.
P H P - ,
. M ySQL
( ).
. ,
,
. , M ySQL
,
. ,
.

22

MySQL

1 - MySQL
, W indows
Mac OS X ( MySQL Linux
).

-
M ySQL ,
, .
, :
,
.
M ySQL - :
, -
MySQL.
, ,
H TM L- .

HTML, - . ,
MySQL, ,
P H P -. -,
,
H TM L-.

, ,
-.

, - .
,
-.
,
. ,
, ,
-. ,
MySQL.

Windows
, -
M ySQL W indow s , W indow s V ista
W indows 7. ,
.
- W indows
.
Apache, MySQL.
.

23

------------------------------------------------------------------------------------------------------------------

Apache,
MySQL ,
. ,
, . ,
-
,
. ,
. ,
, ,
?
MySQL .
, .
.
,

,
.
.

1. W indows Apache Friends


http://wvvw.apachefriends.org/en/xampp-windows.html (
1.7.7 W indows 81 ).
, .
, ,
(. 1.1).

1.7.7 Win32

:
Welcome to the 1.7.7 Setup
Wizard
This wizard w$ guide you through the installation of XAMPP

1.7.7.

It is recommended that you dose all other applications


before starting Setup. This will make it possible to update
relevant system files without having to reboot your
computer.
ClickNext to continue.

. 1.1.

24

MySQL


(UAC)
Windows

(. 1.2).
.

. . .

U J wi

Important! Because an activated User Account Control (UAC) on your sytem some
functions of XAMPP are possibly restricted. With UAC please avoid to install
XAMPP to C:\Program Files (x86) (missing write permisssions). Or deactivate UAC
with msconfig after this setup.
^

. 1.2.
(U A C )

2. ,
.
C:\Program Files, ,
, .
C:\xampp.
3. ,
. c:\xampp
(. 1.3). , (
, ), .
C:\Program Files ( ),
W indows ,
.
Destination Folder

. 1.3.

4. . ,
, (. 1.4).
,
Create desktop icon. , Apache
MySQL (
, ), Install
Apache as service Install MySQL as service .
, .

25

DESKTOP
Create desktop icon
START MENU

Create an Apache Friends XAMPP folder in the start menu


SERVICE SECTION
Install Apache as service
Install MySQL as service
Install Rlezilla as service

. 1.4.

5. ,
( Control Panel). No,
,
. .
6. (
).
(http://www.apachefriends.Org/f/viewtopic.
php?f=16&t=48484),
.
,
.
Apache Friends Control Panel. W indows
(
), Control Panel (. 1.5).
Panel Appli
Control
**...... vvfr?
Control Panel
Modules

Status
Apache

Start

| I A dm in...]

Q S vc

MySql

Start

O S vc

FileZilla

[start

| [ A d m in ...)

Q S vc

Mercury

1 Start

O S vc

Tomcat


E E
T? *o
< <

Start

E
<

O S vc

Refresh

| Explore... |
I

Help

Ex*

XAMPP Control Panel Version 2.S (16. March, 2011)


Windows 6.1 Build 7601 Platform 2 Service Pack 1
Current Directory: c:\xampp
Install(er) Directory: c:\xampp
WARN:This program must be run from your XAMPP root director;
INFO:Perhaps this program running on a 64 bit plattform pie.

a_J
I"' if >
. 1.5. XAMPP

26

1:33 PM
1/5/2012

MySQL

Start Apache MySql ,


-, .
Running.
W indows ,
, Windows Firewall ,
- (. 1.6). ,
.
^

Windows

Windows

Windows
.
:

Apache Software Foundation

: V.a\apache^>inVittpd.exe

Apache :
| / j , ,
, , ( ,
)

. 1.6. ,
- Apache

, , , ,
. -
, .
(
, , ).
, ,
.

?____________________________
, Apache MySQL
. ,
- (, IIS Microsoft
Apache) MySQL. Apache HTTP Server

27

MySQL Windows,
. , -
IIS Microsoft, ,
(http:/Aechnet.microsoft.com/en-us/Iibrary/cc732317(WS.10).aspx).
WampServer .
?
Windows (http://www.apachefriends.org/en/faq-xampp-windows.
html#nostart), Skype (
-).

, Admin
Apache. h t t p : / / l o c a l h o s t / /.
Windows (. 1.7).

ED for Windows

E nglish / D *utsch t Fr*n<is / Nd*rl rtds / Polsld / IU li n o /


Norwegian / Espaftol/ / Portugu&s (Brasil) / S * R

XAMPP
1 .7 .7

Welcome to XAMPP fo r Windows!

P H P ; 5 ,3.81

Congratulations:

You have successfully Installed XAMPP on this system!

svVelcoms
Status
Security

Now you can start using Apache and Co. You should first try Status on the left navigation to make sure
everything works fine,

Documentation
Components

'

- ' ;

"

'

'

/ .

' '

For OpenSSl support please use the test certificate with https://127.0,0.l or httPs://localhost

Good luck, Kay Vogejgesartg + Kai Oswald' Sekfler


CO. Collection
Biorhythm
Instant Art
Phone Book
P erl

perlinfo()
Guest Book

-F F1'/ FF
*

J2EE
Status
"omcat examples

Tools
phpMyAdasn
Webafeer
Mercury Mail
FileZflla FTP

F FFr

''

APACHE
FRIENDS...

. 1.7.

, , -
. , URL
http://localhost/ (
http://), localhost
, .
-, -,
http://local host/.

28

MySQL

, , Exit.
,
W indows ( , ).
, , .
_________________
&

, Apache MySQL
.
, ,
, Stop.
Facebook.

W indows
, MySQL .
MySQL , ,
.
M ySQL r o o t ,
. ,
, ,
.

?
MySQL, -,
. ,
,
MySQL .
.

,
. , Apache M ySQL ,
http://localhost/security/ ( Security
).
,
. The MySQL admin user root has NO
password ( MySQL ).
, .
,
MySQL.
. PhpMyAdmin authentication (cookie)
,
( , ,
). Password changing,
, MySQL,
.
,
( 10 , ). ,
MySQL .

29

MySQL (WINDOWS)
:______________

,
________________________________________________
,
. .
- ,
, ?
,
-, , .

- , .

Mac OS X
, -
MySQL Mac OS X 10.5 (Leopard).
, .
Mac OS X ,
Apache ( , ,
, Ruby, Python Perl).
, . ,
MySQL.

(
Mac, Apache, MySQL ).
- Apache,
MySQL. .


Mac OS X Apache
MySQL. ,
, .
, -
,
. ,
. ,
, ?
MySQL .
, .
.
, ,

,
.
.

30

MySQL

1. http://www.mamp.info
( 2.0.5 116 ).
: ,
PRO. ,
MAMP.pkg.
(. 1.8).
......

______.:-........ :___ -:.

Welcome to the installer

Introduction
You

Read Me

be guided through the steps necessary to

install this software.


License
Destination Select
Installation Type
Installation

Co Back

( Continue

. 1.8.

. - ,
.

2. , .
Install Customize
PRO (
, ). ,
PRO
.

(D

?
PRO,
. Applications,
PRO PRO Uninstaller.
, Uninstall.
.

Applications .
, .
(. 1.9), ,
Apache MySQL.

(. 1.10).

31

, , - ,
. , URL
http://localhost:8888/ (
http://), localhost ,
, 8888 ,
.
.0

manage your website locally


t

Test pro

Status
Stop Servers
Apache Server
Open start page

MySQL Server
Preferences...
Quit

. 1.9.

JT+

Start

0 http7/localhost8888/MAMP/?languagEnglish

phplnfo

XCache

phpMyAdmin

SQLiteManager

FAQ

Welcome to MAMP
ff you can see this page, MAMP is installed
on your Mac and everything is working!

. 1.10. ,
Apache, MySQL

t
, ,
. , 80-
, URL.
, Apache 8888,
a MySQL 8889. ,
-, 80- , MySQL,
3306 ( M ySQL-)1.
1 , ,
8888 8889. ,
.

32

MySQL

, - 80-
, MySQL 3306.
, , .
1. Stop Servers ,
.
2. Preferences Ports.
S

3. Set to default Apache and MySQL ports, 80


Apache 3306 MySQL. .
4. Start Servers. ,
, -
(, 80),
.
, Open start page
, http://localhost/ (
). , !

, ,
, . ,
- M ySQL-,
. Sharing .
Web Sharing , - Apache, Mac OS X
( , 80- ). ,
. Skype Mac OS X M ySQL
.

(8888 8889), . ,
, http .//local host/, (http://
local host:8888/). , MySQL, ,
.
, ,
, .
, ,
Apache -.
,
,
. , ,
. , ,
. .
,
Applications. bin/php/
, . ,
, . ,
( 2.0.5 php5.3.6)
conf. (
, T extEdit) php.ini .

33

1
; Print out errors (as a part of the output). For production web sites,
; you're strongly encouraged to turn this feature off, and use error
logging
; instead (see below). Keeping display_errors enabled on a production web
site
; may reveal security information to end users, such as file paths on
your Web
; server, your database schema or other information,
display.errors = Off

O f f On .
Stop Servers Start Servers, Apache
. (
) .
( ),
, Quit. ,
.
, Mac OS X .
MySQL.
M ySQL , ,
.
M ySQL r o o t ,
. r o o t
. , ,
,
.
?
MySQL, -,
. ,
,
MySQL .
.

MySQL, ,
.
Terminal, Mac OS X ( Utilities
Applications), ,
Enter.
cd

/A p p lic a tio n s /M A M P /L ib r a r y /b in /

Library/bin/ ,
. .

. /m y s q la d m in

-u

root

p a ssw o rd

" newpassword"

newpassword ,
MySQL. Enter,
r o o t .

34

MySQL

.
, , :
MySQL,
. Open start page,
: Error: Could not connect to MySQL server! ,
MAMP MySQL.
,
. ,
TextEdit.

- MAC OS X TextEdit_____________
TextEdit PHP-, HTML,
.
, Ignore rich text

commands.
/Applications/MAMP/bin/mamp/index.php
, :
$link = @mysql_connect(1:/Applications/MAMP/tmp/mysql/mysql.sock',
1root', 'root');

r o o t
MySQL ( newpassword).
/Applications/MAMP/bin/phpMyAdmin/config.inc.php
,
, :
$cfg['Servers'][$i]['user'] = 'root'; // MySQL user
$cfg['Servers'][$i]['password'] = 'root'; // MySQL password (only
needed with 'config' auth_type)

r o o t
MySQL ( newpassword).
/Applications/ P/bin/checkMysql.sh
/Applications/MAMP/bin/quickCheckMysqlUpgrade.sh
/Applications/MAMP/bin/repairMysql.sh
/Applications/MAMP/bin/stopMysql .sh
/Applications/MAMP/bin/upgradeMysql.sh

( checkMysql.sh):
# /bin/sh
/Applications/MAMP/Library/bin/mysqlcheck --all-databases --check
--check-upgrade -u root -proot --socket=/Applications/MAMP/tmp/mysql/
mysql.sock

35

- p r o o t ? password, .
r o o t ( - newpassword).
.
,
MySQL,
.
,
( 10 , ).
MySQL .
MySQL (MAC)_______________________
:_____________________ .

Linux
, Linux ,
,
, Apache, MySQL. ,
, .
- .
,
Apache, MySQL, ,
. , ,
, - .
Linux,
, .

-
MySQL ,
-. ,
.
, .
P H P - , , HTM L- CSS-,
-. , ,
.
-, ,
(F T P SFTP), ,
'. ,
, ,
.
, MySQL,
-: ,

36

MySQL

( , localhost), MySQL
( (S )F T P ). ,
- ,
, M ySQL-.
.
-,
.
__________________________________

( ):

FTP
SFTP

(S)FTP-cepBepa:

__________

(S)FTP:

__________

(S)FTP:

__________

MySQL-

__________

MySQL:

__________

MySQL:

__________

MySQL:

__________

-

, ,
-.
.
H TM L-
today.php ( c h a p t e r l / t o d a y . p h p ). .
<!DOCTYPE html>
chtml lang="en">
<head>
cmeta charset="utf-8">

<title>CeroflHHffiHHH flaT a</title>


</head>
<body>
<> ( -):
<?php
echo date('l# F jS Y . ');

?>
</p>
</body>

</html>

37

,
:
echo date('1, F jS Y . ');

.
. (1), L (1).

- WINDOWS _________
.php ,

.
today.php.txt, .

- MAC OS X TextEdit_____________

TextEdit
PHP-. Rich Text Format
(RTF), .rtf.
PHP-, ,
TextEdit Format Make Plain Text (ft+3+T).
. PHP- TextEdit
HTML,
. ,
Ignore rich text commands.


________________________________________________
,
, ,
PHP-.
,
(Integrated Developm ent Environment, IDE)
. : NetBeans (http://www.netbeans.org/features/php/),
A ptana (http://www.aptana.com/php), Kom odo (http://www.activestate.com/komodo_edit/).
Windows, Mac OS X Linux,
.


-.
-_____________
Apache ,
htdocs ,
: C:\Program Files\Apache Software Foundation\Apache2.2\htdocs Windows /
usr/local/apache2/htdocs Linux.
Apache htdocs
, . ,
Apache Friends htdocs
folder.

38

MySQL

Apache, Mac OS X,
/Library/WebServer/Documents.
Open Computer Website Folder Web Sharing,
Sharing .
Apache htdocs
, (/Applications/MAMP/htdocs).
,
Apache. ,
,
-.

http://localhosVtoday.php ( http://
localhost:!.php, Apache 80),
, 1.
URL____________________________________
-
,
.
PHP- . ,
- HTML
PHP- .
-, URL (http://localhost/today.php).

. 1.11 , -,
-.
() - Mozilla Firefox
iocalhost/today.php

-V

( -): Tuesday, March 19th 2013.

. 1.11. -

, ? ,
H TM L- . (,
< ?p h p ?> )
, .
, ,
, -.
1 Apache Windows , ,
8080, 8888.

39

, , .
3 , .
-
, , , - -
. , ,
. ,
< ?php ... ? > H TM L- . ,
-, (
URL, http://localhost/),
, - .
, , .



: -, -,
M ySQL ,
. ,
.
today.php , SitePoint
(http://www.sitepoint.com/forums/),
.
2
MySQL. ,
(Structured Query Language, SQL).
,
.

2
MySQL

1 : - Apache
MySQL.

.
,
, . H TM L-
,
( , Apache). ,
-. ,
.
, .
MySQL. , ,
MySQL .


( MySQL) ,

, . ,
,
.
.
. -,
HTM L-,
P H P -,
-. -, ,
.
.
,
. ,
, . ,
joke (),
.
, .
. joke :
, .

41

, .
(. 2.1).

I
joketext

jokedate

...

2012-04-0

-! ...

2012-04-0

. 2.1. ,

, , ( j t e x t )
(j o k e d a t ), id . ,

. ,
,
j o k e t e x t j o k e d a t . i d
, .
5.
, . 2.1 ,
, . :
, . ,
, MySQL.

phpMyAdmin
SQL-
- ,
MySQL .
MySQL -,
phpMyAdmin, .
- phpM yAdmin .
,
- MySQL.
.
, MySQL, phpMyAdmin
.
phpMyAdmin?_____________________________________________

, - ,
, , ,
phpMyAdmin. phpMyAdmin
http://www.phpmyadmin.net/.
.

42

MySQL

XAM PP Windows, phpMyAdmin


, Admin MySql
(. 2.2).

Control Panel
Modules

Status H

O Svc

Apache

Running

HSvc

MySql

Running

h Stop

BSvc

FileZifla

(J Start 3

Svc

Mercury

Svc

Tomcat

(I Start

Stop 3

Start

[ Admin... j
]

p i2 m in ...|

f Refresh [
f Explore., j

f A dm in... f
)

Adm:

] I A dm in... J

Current Directory: c:\xampp


Install(er) Directory: :\
WARN:This program must be run from your XAMPP root director;
INFO:Perhaps this program running on a 4 bit plattform pie;
Busy-Apache started [Port 80]
Busy...
MySql started [Port 3306]

. 2.2. Admin phpMyAdmin

phpMyAdmin Mac OS X,
Open start page phpMyAdmin
(. 2.3).
Start

phplnfo

XCathff

phpMyAdm in

SQLtteM am gef

FAQ

Try M A M P

Welcome to MA
if you can see this page, MAI
on your Mac and everything

MAMP

manage your website locally

To it* th PHP xn figuration, you i n watch th * output of ohointo.

St I StopServttfj

MySQL
The M ySQL D ita b a vt c*n b * adm tntttnt*d wtth
To connect to ho M ySQL Server from yo u r own crip use the forte

ovomotort:

. 2.3. phpMyAdmin

, phpMyAdmin (. 2.4).
phpMyAdmin
3.5 (
). 3.3
, .

43

kxalhoit / 127.0.0.11phpMyAdmin 1322 - Moalte firefox

jjjjjll

(< 3 *

..............
_............ ............... l

' S ' l o c a lh o s t / p h p m y a d m in /

phpMyAdmin
&i e *

127 0 0 1
i 3 i

^ .v.4*i.M.wt

SQL

*:
-,vv>

cdcoi

infbrmationschema

nrtysql

performance_schsma

3 phpmyadmtn
3 test
3

webauth

W
$$>

: 127.0.0.1 via TCP/IP


; MySQL
6 5.27 - MySQL
Community Server (GPL)
* : 10
. root@Jocalhost
* : UTF-8 Unicode (utffi)

MySQL :
j ut_general_ci


iP - Language . - Russian

41 ! pmahomme [
: 82%

Apache/2.4 3 (Win32) OpenSSL/1.0, 1


/5.4.7
libmyscfl mysqtnd 5.0.10 - 20111026 - :
5c693b?f8aeb3aa66b646fee339f175

5
: mysqt #

phpMyAdmin
: 3.5.2.2,
3.5.7

phpMyAdmin

'

. 2.4. ,
, phpMyAdmin

phpMyAdmin ,
, MySQL- ,
.
SQL-.
phpMyAdmin .
(. 2.5), SQL- (. 2.6).

phpU

1Admin

1 )
1

( ; ...

:;

. 2.5. SQL-

,
.
, M ySQL-.

44

MySQL

localhost / 127.0.0.11phpMyAdmin 3.5.22 - Moziila Firefox

... .

.php?lang=: ru&coHation_connection= utf8_general_ci&token=52e73e4c28349a29c7cd2faf9842da.

SQL
V

@> SQL-

----------- _ -------------------

U.----------- .-------

SQL-3anpoc(bi) **127.0.0.1":

-^- - ,

: j

] }

......

. 2.6. SQL-

MySQL .
-
MySQL.
, .
.
SQL- .
SHOW DATABASES

, ,
phpMyAdmin (. 2.7).
,
, . 2.7.
, M ySQL-
.
i n f o r m a t io n _ s c h e m a m y s q l.
MySQL (
, ).
MySQL , .

45

10
MySQL.
^mimnrrmnnim 1 1!1....11111111|11111111!1111 .

SQL-

...

SHOW DATABASES

information_schema
cdcol
mysql
j

performance schema
~~
phpmyadmin

'I B H H H H I
webauth
. 2.7.
phpMyAdmin

t e s t ,
MySQL ( ). ,
.
MySQL DROP ():
DROP DATABASE test

SQL-
, , phpMyAdmin DROP
DATABASE ( ) . phpMyAdmin
.

46

MySQL

phpMyAdmin,
phpM yAdmin ( )
. ,
( t e s t ) , (. 2.8).

cdcol

mysql

phpmyadmin

id test J
H

webauth

/ :

. 2.8.
phpMyAdmin

phpM yAdmin ,
. MySQL
, a phpMyAdmin ,
.
DROP DATABASE, ,
MySQL. phpMyAdmin
. SQL-,
,
.


, MySQL,
(Structured Query Language, SQL).
.
.
SQL ,
. M ySQL
Microsoft SQL Server, ,
. SQL MySQL: MySQL ,
, a SQL ,
.

47

2
CREATE TABLE _ (
1 1 1,
2 2 2

) DEFAULT CHARACTER SET charset ENGINE=InnoDB

j o k e ,
. 2.1. , : i d ( ),
j o k e t e x t ( ) j o k e d a t ( ).
.
CREATE TABLE joke (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
joketext TEXT,
jokedate DATE NOT NULL
) DEFAULT CHARACTER SET Utf8 ENGINE=InnoDB

, ? .
CREATE TABLE joke (

. ,
j .
.
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,

, i d
integer ( IN T ), .
:
, ( NOT
NULL);

, , ,
MySQL ,
(AUTO_lNCREMENT );

,
(PRIMARY KEY).
joketext TEXT,

, j o k e t e x t ,
( TEXT).
jokedate DATE NOT NULL

j o k e d a t ,
(DATE). (NOT
NULL).
) DEFAULT CHARACTER SET utf8

50

MySQL

.
DEFAULT CHARACTER SET u t f 8 MySQL, ,
, UTF-8.
-,
.
ENGINE=InnoDB

MySQL ,
.
, .
, JP E G ,

PNG. ,
. MySQL
.
InnoDB ,
(
). MySQL
MylSAM, ,
InnoDB.
,
: i d , j o k e t e x t , a j o k e d a t e
. MySQL ,
,
. , MySQL,
.
, .
, phpMyAdmin ,
, . phpM y Admin
, , ,
MySQL .
, .
SQL- .
SHOW TABLES

phpMy Admin , . 2.11.


joke
. 2.11. phpMyAdmin

i j d b .
j o k e , .

51

. ,
DESCRIBE.
DESCRIBE joke

. 2.12, j o k e ( ),
.
, .
, .

. 2.12. phpMyAdmin j

, ,
.
DROP DATABASE, phpMyAdmin
.
j , !
, , .
DROP TABLE


, ,
. , ,
INSERT. .
INSERT INTO SET
1 = 1,
2 = 2,

INSERT INTO
( 1, 2, ...)
VALUES (1, 2, ...)

,
.
INSERT INTO joke SET
joketext = " ?
!",
jokedate = "2012-04-01"

52

MySQL
INTO joke
(joketext, jokedate) VALUES (
" ? !",
"2012-04-01")

insert

, ,
INSERT , .

.
.
, , ,
().
.
SQL. ,
" YYYY-MM-DD".
( 1).
INSERT INTO joke SET
joketext = ' ?
!',
jokedate = '2012-04-01'

, ?
,
, , .
, ,
, ,
(\). MySQL ,
.
MySQL ,
.
, ,
INSERT , ,
.
INSERT INTO joke
(joketext, jokedate) VALUES (
'" - , - , - ...", , , \' .',
"2012-04-01")

,
.
. , M ySQ L ,
,
.
SQL- ?
( \ \ ) . MySQL ,
.
, , , ,
.

53


SELECT, ,
, SQL.

. ,

SELECT.
, j .
SELECT * FROM joke

joke. ,
, ,
. 2.13.

1 ? .

2012-04-01

. 2.13. phpMyAdmin j

, -
.
MySQL j t e x t .
SELECT id, jokedate FROM joke

,
. , . 2.14.
id jokedate
1 2012-04-01
. 2.14. ,

?
, SELECT
. ,
20 j o k e t e x t .
LEFT, .
SELECT id, LEFT(joketext, 20), jokedate FROM joke

. 2.15.
COUNT
. , , ,
.

54

MySQL
SELECT COUNT(*) FROM joke

id - LEFT(joketext, 20)

jokedate

1 2012-04-01
. 2.15. LEFT

. 2.16, .

1
. 2.16. COUNT

.
,
.
SELECT WHERE.
.
SELECT COUNT(*) FROM joke WHERE jokedate >= "2012-01-01"

1
2012 . ,
. , ,
. :
SELECT joketext FROM joke WHERE joketext LIKE "%%"

,
j o k e t e x t. LIKE MySQL ,
1.
" %%". % , ()
.
WHERE ,
. ,
', 2012 ,
.
SELECT joketext FROM joke WHERE
joketext LIKE "%1%" AND
jokedate >= "2012-04-01" AND
jokedate < "2012-05-01"

1 L I K E ,
, .

55

, .
,
, HTML, CSS JavaScript.
JavaS cript,
( ) H T M L - -.
H TM L
. JavaS cript
-,
.
, JavaScript ,
,
. ,
, - ,
. ,
,
, .
P H P - -
. , H TM L-
. today.php,
1 ( c h a p t e r 3 / t o d a y .p h p ) .
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<1:::1>1 flaTa</title>
</head>
<body>
<> ( -):
<?php
echo date('l, F jS Y.');

?>
</p>
</body>
</html>

HTML,
< ? p h p ?> P H P -. < ? p h p

58

P H P -, ?> . - ,
,
HTM L- - ,
. .
< iDOCTYPE html>
chtml lang="en">
<head>
cmeta charset="utf-8">
<^^1> flaTa</title>
</head>
<body>
<> ( -):
Sunday, March 24th 2013.
</p>
</body>
</html>

, P H P - .
, H TM L-.
.
, .
P H P - -,
,
, .
. -
, . JavaScript
, .

, ,
MySQL.
. JavaScript
- ( ),
, ,
. -,
,
( ).



, JavaScript, , C++,
#, Objective-, Java, Perl , .
, .
- , .
, ,
- . ,
(;).

59

,
.
.
, .
, .
/ / .
, / * * / .
,
.
.
. , ,
.
$testVariable = ' ' . '!'; // ' !'

,
. .
$varl = ''; // '' $varl
$var2 = 5; // 5 $var2
$var3 = $var2 + 1; // 6 $var3
$var2 = $varl; // '' $var2
echo $varl; // ''
echo $var2; // ''
echo $var3; // '6'
echo $varl . ' - !1; // ' - !'
echo "$varl
- !"; // ' - !'
echo '$varl
- !'; // '$varl - !'

.
,
.
. ,
, ,
.

. ,
, ,
.
a r r a y .
$myArray = array('', 2, '3');

$m yA rray, :
' ', 2 13 '. ,

62

.
, .
, ,
. ,
: ( ) 0, 1,
2 . , - - 1. ,
,
.
echo $myArray[0]; I I ''
echo $myArray[1]; I I '21
echo $myArray[2]; // '3*

, , .
,
.
$myArray[l] = '';- //
$[3] = ''; //


. ,
, .
$myArray[] = ' ';
echo $myArray[4]; // ' '

, ,
.
, () ,
.
, .
$birthdays[''] = '1978-04-12';
$birthdays[''] = '1980-05-16';
$birthdays[''] = '1983-09-09';

a r r a y .
$ b i r t h d a y s .
$birthdays = array('' => '1978-04-12',
'' => '1983-09-09');

'' => '1980-05-16',

, ,
:
echo ' :

' . $birthdays[''];

,
.
.

63



, , ,
, , ,
, .
JavaScript-
, ,
. ,
, , .
P H P - , ,
:
,
1.
,
-.
.


, -,
URL. ,
, , .
, Google SitePoint,
URL .
http://www.google./search ? h l = e n & q = S i t e P o i n t

URL? , ,
, (SiteP oint)?
http://www.google.com/search.
. HTM L-
name.html ( .php ,
P H P - ) ( c h a p t e r 3 / l i n k s l /
n a m e . h t m l , ):
< href =" name. ]1 ?=">, !</>

name.php,
, .
, URL
1 JavaScript Ajax-,
. JavaScript
- PHP-. ,
, ,
Ajax. (Earle
Castledine) (Craig Sharkie) j Query (Query: Novice to Ninja).

64

. name . ,
, name.php P H P - ,
name .
, ,
name.php. H T M L -,
.php. - , .
body (chapter3/linksl/name.php,
):
<?php
$nam e = $_GET['n a m e ' ] ;
echo ' -,

$name

?>

(name.html name.php) -
. URL http://localhost/
name.html ( http://localhost:8888/name.htmI, - 80-
). , ,
-. :
, ! (. 3.1).
, - Mozilla F
localhost/name.php?name=:

'

. 3.1. ,

, .
(chapter3 /linksl/name .php, ):
$name = $_GET['name'];

, ,
. $name ,
' name ' $_GET. $_GET?
$_GET ,
.
, , URL.
, name,
, $_GET [' name1].

65

name.php ( $ ),
, echo (chapter3/linksl/
na m e .php, ).
echo

' -,

' . $name . '!';

$name
(.), ,
.
,
. ,
, ,

. , ,
name.php, (
$name).
name.html, URL
.
, , name.html .
, URL
. :
http://localhost/name.php?name=KeBHH

URL, b /:
http://localhost/name.php?name=<b>KeBMH</b>

Enter, .
(. 3.2)1.
5

II' .' _' II' III III1_I 1_11_|_> !'l

-------------------------------------------------------------

^-------------

, - Mozifla F*.
localho$t/name.php?name=b>/>

V I

-, !

. 3.2.
1 , ,
< > , URL (% %
). .

66

, URL H TM L-,
-
. ,
JavaScript , , .

, .

. ,
!
,
P H P - ,
. :
, .
,
.
,
.
, ,
? ,
, $name,
, , HTML,
.
name.php ,
(chapter3 /links2 /.php, ):
<?php
$name = $_GET[''];
echo -, ' .
htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '!';

?>

. :
$ '' $_GET.
echo .
$ ,
htmlspecialchars,
.
, name.php - ,
$name,
HTML. htmlspecialchars
H TM L- < > &lt ; &gt;.
H TM L-.
, htmlspecialchars.
.
htmlspecialchars($name, ENT_QUOTES, 'UTF-8')

67

$name (,
). 1 ENT_QUOTES,
htmlspecialchars, , ,
.
1UTF-8 ', ,
.

UTF-8
Jjgj|i ------------------------------------------------------------------------------------------------ ---------------- , HTML-
met :

<meta charset="utf-8">
, , ,
UTF-82. ,
, ,
.
, h t m l s p e c i a l c h a r s , ,
ISO-8859-1 ( Latin-1).
, , UTF-8.
(,
, ) , (
, ), ,
HTML- PHP- UTF-8. , ,

HTML (, & rsq u o ;
), , .

name.html ,
name.php.
-, !. URL,
b / .
h t t p : / / localhost/nam e.php?name=<b>KeBHH</>
Enter
(. 3.3), , .
, ,
htmlspecialchars < >,
, H TM L- &lt ; &gt;.
,
, .
1 , .
$. ,
.
2 UTF-8 ,
.
The definitive guide to web character encoding (
) http://www.sitepoint.com/article/guideweb-character-encoding/.

68


_---- ------- j-----; -
{
, - Mozilla F. 1)-

I
localhost/name,php?name=: < b> </b>

-!

--- 1

- <><>!

1 81

_____

_____ !_____ S
____ !

. 3.3. ,

htmlspecialchars,
. ,
. ,
.
P H P - .
, .
.
. name.html
, name.php,
(chapter3/links3/name .html, ):
< href= "name.php?firstname=KeBMH&amp;lastname=HHK">,
!</>

: firstname lastname,
( &, HTM L
URL & ;). =
, .
name.php (chapter3 /
1inks3 /n a m e .php, ).
<?php
$firstName = $_GET [' f irstname '] ;
$lastName = $_GET[lastname'];
echo ' -, 1 .
htmlspecialchars($firstName, ENT_QUOTES, 'UTF-8') . ' ' .
htmlspecialchars($lastName, ENT_QUOTES, 'UTF-8') . '!';

?>
echo , ,
. (.),
-,
$f irstName, , $lastName .

69

$f irstName $lastName htmlspecialchars


. . 3.4.

-, !

. 3.4.

,
.
, ,
, -.
H TM L-.


name.html H TM L-
(chapter3/formsl/name.html, ).
<form action=".php" method="get">
<div><label for="firstname">:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n
bsp;&nbsp;
<input type="text" name="firstname" id="firstname"></label>
</div>
<divxlabel for="lastname">:
<input type="text" name="lastname" id="lastname"></label>
</div>
<divxinput type="submit" value= ""x / d i v >
</form>

, , . 3.5.
-

- Mozilla Firefox

9 localhost/name.html
:

. 3.5.

70


, . ,
CSS ,
. MySQL,
.
CSS, The CSS3 Anthology (
CSS3) SitePoint (http://www.sitepoint.com/books/cssant4/).

,
, (
f i r s t n a m e = K e B H H & a m p ; l a s t n a m e = H H K ),
.
, name.php,
. ,
< i n p u t t y p e = " t e x t ">, ,
.
______________________________________
, (,
),
: -, '!

, .
4.

m e th o d , fo rm , ,
.
g e t , name.html,
( $_GET).

. t e x t a r e a ,
? ,
,
URL, .
, .
name.html. m e t h o d ,
p o s t ( c h a p t e r 3 / fo r m s 2 / n a m e . h t m l , ).
<form action="name.php" method="post">
<divxlabel for="firstname">:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n
bsp;&nbsp;
<input type="text" name="firstname" id="firstname"></label>
</div>
<div><label for="lastname">:
cinput type="text" name="lastname" id="lastname" x/label>
</div>
<divxinput type="submit" value= ""x / d i v >
</form>

m e t h o d
, ,
URL.

71

,
$_GET .
$_PO ST, , post.
, ,
name.php (chapt / forms2 /name.php, ).
<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
echo ' -, ' .
htmlspecialchars($firstname, ENT_QUOTES, 'UTF-8') . ' ' .
htmlspecialchars($lastname, ENT_QUOTES, 'UTF-8') . '!';

?>

, . 3.6.
)

- ... .
, - Mozilia Firefox IJEL3 =

Q j localhost/name.php

L j B k H I

fV r C?

-, !

. 3.6. ,

.
,
, ,
. ,
( ,
), . ,
,
, ,
.
.
Google,
,
URL.
,
.
$_REQUEST. ,
$_GET $_POST.
,
(chapt / forms3 /name.php, ):

72


<?php
$firstname = $_REQUEST ['firstname'];
$lastname = $_REQUEST['lastname'];
echo ' -, ' .
htmlspecialchars ($f irstname, ENT_QUOTES, 'UTF-8') . ' ' .
htmlspecialchars($lastname, ENT_QUOTES, 'UTF-8') . '!';

?>

.
.


P H P -
, -,
, . -
(JavaScript, Objective-, Ruby Python),
, .
, ,
.
, ,
.
.

i f . . 3.7.

. 3.7. i f
1 , ,
(Cameron Adams) Simply JavaScript ( JavaScript; :
SitePoint, 2006), , .

73

i f .
if ( )

{
: f ,

}
,
- .

. name.html,
. , :
name.php name (chapter3/if /name.html,
).
<form action="name.php" method="post">
< d i v x l a b e l for="name">JlMH:
< input type="text" name="name" id="n a m e "></label>
</div>
<div><input type="submit" value=""/></div>

</form>

name.php. P H P -
( c h a p t / i f / n a m e . p h p , ).
$name = $_REQUEST[''];
if ($ == '')

{
echo ' , !';

>
, n a m e ' ' ,
(. 3.8).
1

_ j 151

(@v

, !

. 3.8.

- ,
: i f
.

74

,
i f e l s e .
. 3.9.

. 3.9. i f e l s e
*

e l s e i f i f e l s e l / n a m e .p h p , ):

e l s e i f

(c h a p te r3 /

$name = $_REQUEST['name'];
if ($name == '')

{
echo ' , !';

}
else

{
echo ' -,
htmlspecialchars($name, ENT_QUOTES,

' .
'UTF-8')

. '!';

>
, ,
(. 3.10).
| ~~> |

- Mozilla Firefox
localhost/name.php

-; !

V
.- ,Tt

:..

-_____ \_____

____ ____ !_____

. 3.10.

75

==
,
.
.

_______________________________________________

(==).
.
if ($name = '') // !


(=), ,
. , $name
'' '' $name.
, i f
, ;
if , ,
$.

,
. , ?
,
.
name.html ,
(chapter3/if else2/name .html, ).
<form action="name.php" method="post">
<divxlabel for="firstname">:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n
bsp;&nbsp;
<input type="text" name="firstname" id="firstname"></label>
</div>
<div><label for="lastname">:
<input type="text" name="lastname" id="lastname"></label>
</div>
<div><input type="submit" value=""></div>
</form>

name.php P H P - (
(chapter3/ifelse2/name.php,
)).
$firstName = $_REQUEST['firstname];
$lastName = $_REQUEST['lastname'];
if ($firstName == '' and $lastName == '')

{
echo ' , !';

}
else

{
echo ' -, 1 .
htmlspecialchars($firstName, ENT_QUOTES, 'UTF-8') . ' ' .
htmlspecialchars($lastName, ENT.QUOTES, 'UTF-8') . '!';

76

,
$firstName $lastName '' '' .
AND ,
. OR ,
.
JavaScript && I I ( AND OR
), .
. 3.11 ,
, .
,
if - else.
- Mozilla Firefox

||| |

localhost name.php

(@ v

-, !

......................................

. 3.11.

while ,
. if - else ,
, while
, .
. 3.12 , while.

. 3.12. w h i l e

77

.
while ( )

{
!

( ) , ,

}
while if.
. while
, (}),
. - ,
,
true. (
), ,
while .

(, , ),
, (chapt /count 10 .php, ).
$count = 1;
while ($count <= 10)

{
echo "$count ";
++$count;

}
, ,
.
$count = 1;

$count,
1.
while ($count <= 10)

. $ count
10.
{
while
, . ,
.
echo "$count

$ count, .
,

(. , ).

78


++$count;

$ c o u n t .
+ + $ c o u n t $ c o u n t = $ c o u n t + l .
.
>
w h ile .
.
$ c o u n t 1 ,
$ c o u n t ( 1),
, 2. ,
2 ,
3. 3 ,4 ,5 ,6 ,7 ,8 ,9 10. ,
$ c o u n t 11,
.
. 3.13.
- Mozilla Firefox

-----------------localhost/countlO.php

. 3.13.

<= (
). : >= (
), < (), > () ! = ( ).
.
, ,
, - (
), f o r .
. 3.14.
f o r .
for ( ; ; )

{
! ( ) , ,

79

. 3.14. f o r

,
( ) (
) .
,
f o r ( c h a p t e r 3 / c o u n t 1 0 - f o r .p h p , ).
for ($count = 1; $count <= 10; ++$count)

{
echo "$count";

}
, , $ c o u n t
, f o r .
,
, : ,
, . f o r
,
.

80


, .
-,
.php P H P - .
!
,
.
, .
, ,
, -.
,
.



H T M L -,
.html, ,
H T M L .php.
,
,
.
, ,
, ,
, - .
URL
,
. ?
URL,
. , ,
,
.
,
, .
URL , -
index.html index.php .
, , today.php 1. index.php.
,
, today.
http://localhost/today/ ( - http://localhost:8888/today/,
). . 3.15
URL.
.php, ,
URL.

81

? v c l 1 '5

localhost/today/

-.

( -): Friday, March 29th 2013.

. 3.15. URL


, ,
P H P - H TM L- .
, ,
HTM L . ,
-, .
P H P -, HTML,
: ,
, .
P H P - ,
HTML.
i n c l u d e , .
, ,
f o r .
countl 0 index.php.
( c h a p t e r 3 /
c o u n t 1 0 / i n d e x . php).
<?php
$output = '';
for ($count = 1; $count <= 10; ++$count)

{
$output .= "$count

}
include 'count.html.php';

He , .
HTM L-. f o r ,
.
1. 1 10 echo,
$ o u tp u t,
.
2. , ,
$ o u tp u t. . = -

82


.
$ o u t p u t = $ o u t p u t . "$c o u n t
3. i n c l u d e , ,
count.html.php1.
, ,
?>, < ?php.
, .
P H P -,
.
.
count.html.php,
( c h a p t / c o u n t 1 0 / c o u n t .h tm l .p h p ).
<!DOCTYPE html>
chtml lang="en">
<head>
cmeta charset="utf-8">
<title>Counting to Ten</title>
</head>
<body>
<P>
<?php echo $output; ?>
</p>
</body>
</html>

H TM L-,
, ,
$ o u t p u t . ,
index.php.
. -
P H P -,
.
, (index.php).

, HTML, ,
- P H P -.
, H TM L-.
- ,
.html.php. - , .html.php ,
HTML-, -.
1 include ,
date htmlspecialchars. ,
, .
echo.

83

,
i n c l u d e
, ,
.
-, ,
, .
, ,
.
,
.
. name.html.
welcome name.html,
form.html.php. a c t i o n f o r m
( c h a p t e r 3 /w e lc o m e /f o r m . h t m l . php):
<1DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ITpHMep <|>opMbi</title>

</head>
<body>
<form action="" method="post">
<div><label for="firstname">:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp
;&nbsp;&nbsp;
<input type="text" name="firstname" id="firstname"></label>
</div>
<divxlabel for=" lastname">:
<input type="text" name="lastname" id="lastname"></label>
</div>
<divxinput type= "submit" value= ""x / d i v >
</form>
</body>
</html>

a c t i o n ,
, . URL ,
.
.
welcome, , index.php.
( c h a p t e r 3 /w e lc o m e / i n d e x . php).
<?php
if (!isset($_REQUEST[1firstname']))

{
include 'form.html.php';

}
else

{
$firstName = $_REQUEST['firstname'];

84


$lastName = $_REQUEST['lastname'];
if ($firstName == 'Kevin' and $lastName == 'Yank')

{
$output = ' , !';

}
else

{
$output = ' -, ' .
htmlspecialchars($firstName, ENT_QUOTES, 'UTF-8') . ' ' .
htmlspecialchars($lastName, ENT_QUOTES, 'UTF-8') . '!';

>
include 'welcome.html.php';

}
name.php,
.
1. ,
form.html.php.
firstname. ,
$_REQUEST [ 'firstname 1].
is set ,
( ). $_REQUEST [ ' firstname ' ]
, isset ( $_REQUEST [ ' f irstname ' ] )
true, false.
, ,
, . i f
, $_REQUEST [ 'f irstname '].
(! ).
, : true false
false true. ,
firstname, ! isset ( $_REQUEST ['firstname1] ) true
if.
2. ,
form.html.php.
3. ,
else.
f irstname lastname
$_REQUEST,
.
4. echo,
$output.
5. ,
welcome.html.php, .
welcome.html.php (chapter3/welcome/welcome,
html.php).

85

3
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=''utf-8">
<title>ITpnMep op</title>

</head>
<body>
<p>

<?php echo $output; ?>


</p>
</body>

</html>

http://localhost/welcome/
( http://localhost:8888/welcome/, - 80- ).
. ,
. URL
.

,
.
( ),
. ,
URL,

- (
).
?____________________________________
9 , .



, , ,
. ,
URL
HTM L- P H P -, .
, , ,
( ) ,
MySQL, ,
Adobe Acrobat PDF.
4 MySQL, ,
, , 2.
,
, MySQL
.

4

MySQL

,
MySQL, -.
(M ySQ L)
( ). ,
.


, - .

MySQL. ,
.
, , ,
-,
. , ,
.
HTM L.
,
MySQL, SQ L ( ). ,
.
M ySQL, SQ L-, ,
2.
H T M L -,
(. 4.1).
, ,
, .
1. - .
2. - ( Apache)
- ,
.
3. (
) MySQL
, .

87

4. M ySQL P H P -
.
5. - ,
- e ch o .
6. ,
HTM L- -.
7. - , H TM L-.
,
, . ,
-.

. 4.1. MySQL -


MySQL
MySQL,
.
, ,

. MySQL
.
1 M ySQL (r o o t ). -
MySQL, , r o o t
. ,
.
, (, ,
),
, .

88

MySQL


, ,
i j d b , .
.
1. phpMyAdmin :
1) W indows
Admin MySql;
2) Mac OS X , Open start page (
),
phpMyAdmin.
2. , , i j d b
(. 4.2).

p h p M y A d m in

( ) .

0 cdcoi
9

ijdb

informkrion_schema

mysql

performance_schema

phpmyadmin

test

webauth

_|

. 4.2. i j d b

3. , (
j o k e ) .
(. 4.3).
127.0.0 1

SQL

*4

Qj

*8
fere*#*-:-:

........................


.^

..

* $

"

_ --------------------------------------------------

**?
2

JL.

InnoOB utf8_general_ci

2 lnnoDB. Mnljawdlshcl

13

. 4.3.

4. i j d b
(. 4.4).

89

&

"ijdb

^ ..

GRANT

al l privileges
localhost al l privileges

. 4.4. , i j d b
root1.
5.
.
. . ,
i j d b . , ,
, .
i j d b u s e r , ( i j d b )
, .
. M ySQL- ,
-, ,
(localhost).
, 2.
. .
mypassword. , , .
, -.
6.
ijdb.
, i j d b ( ).
7. .

.
.
8. .

1 root , MySQL
. 1- 127.0.0.1,
localhost. ,
, -.
- 10.
2 .
, 10.

90

MySQL

9. phpMyAdmin
SQ L-, (. 4.5).
( )
MySQL.
t fl 127.0.0.1 ijdb
.

SQL

(3

CREATE USER ,ijdbuser,@ ,locaihost' IDENTIFIED BY

.' '

. .
:

GRANT USAGE ON * * 4]dbUSer<@'localhOSt* IDENTIFIED BY


' WITH MAX_QUERIES_PER_HOUR 0
MAX_CONNECHONS__PER_HOUR 0 MAX_UPDATES_PER._HOUR 0 MAXJJSER ^CONNECTIONS 0 ;
GRANT ALL PRIVILEGES ON ijd b '. * TO ,ijdbuser@ ,localhost;
[
^

. 4.5. phpMyAdmin ,

MySQL

-, , MySQL
P H P -. -
phpMyAdmin, P H P -
M ySQL- .
D ata Objects (PD O ).
MySQL PDO.
new PDO('mysql:h o s t = _ ;dbname = _ 1, ' _ ' ,
' ')

new PDO ,
, , d a te , 3.
, , ,
. , , ,
. :
1) ( m y s q l :),
(host=HMH_cepBepa) (11=__);
2) MySQL, ;
3) .
, , , , ,
. new PDO P D O ,

91

.
, .
new PDO ,
, (chapter4/connect/index.php,
):
$pdo = new PDO('mysql:host=localhost;dbname=ijdb', 'ijdbuser',
'm y p a s s w o r d ') ;

, M ySQL-
, , , ijdbuser
, mypassword. , ,
new PDO, $pdo.
, M ySQL -
. ,
, , - ,
- ,
. new PDO
.
,
, . , , ,
. ,
() . ,
- .

!___________________________________________________________
,
, ,
, . ,
MySQL, ,
!

, ,
, try catch:
try

{
: -

>
catch (E x c e p t i o n T y p e $)

{
i

}
try catch if else. ,
,
.
?
.

92

MySQL
try

{
$pdo = new PDO('mysql:host=localhost;dbname=ijdb', 'idjbuser',
'm y p a s s w o r d ');

}
catch (PDOException $e)

{
$output = ' .';
include 'output.html.p h p ';
exit();
}3

, try - catch. try


new PDO.
PDO $pdo
. ,
PDOException ,
new PDO. catch PDOExcept ion
$. $ output ,
, .
output.html.php ,
$output (chapter4/connect/output.html.php).
<!DOCTYPE html>
<html lang="en">
<head>
cmeta charset="utf-8">
<title>BHBOfl C K p n n T a < / t i t l e >
</head>
<body>
<P>
<?php echo $output; ?>
</p>
</body>
</html>

,
catch exit. ,
. exit ,
- ,
(, ,
) .
, . ,
. , new PDO .

PD O ( Data
Objects). new PDO . ,
.
,
-

93

(). ,
-
.
, .

.
P H P -,
, .
, .
,
W ordPress (http://wordpress.org/).
PDO, MySQL
, - . ,

PDO,
,
.
(chapter4 /connect /
index.php, ).
$pdo = new P D O ('mysql:host=localhost;dbname=ijdb', 'ijdbuser',
'm y p a s s w o r d ') ;

new ,
. , ,
.
, ,
. , new PDO
, PDO.
,
. ,
. ,
.
, .
. 3 ,
(, birthdays [ 1 ' ] ).
,
-.
, ,
. , $myObject->someProperty.
$myObject = new SomeClass(); //
$myObject->someProperty =123; //
echo $myObject->someProperty; //

, (,
), , ,
(, ).

94

MySQL

, :
. , .
,
. ,
, . , .
, $ m y O b je c t-> s o m e M e th o d ().
$myObject = new SomeClassO; //
$myObject->someMethod(); //


.
,
.
() () ,
,
. .
, - ,
,
. PD O ,
.


, PD O MySQL
,
.
try

{
$pdo = new PDO('mysql:host=localhost;dbname=ijdb', 'idjbuser',
'm y p a s s w o r d ');

}
catch (PDOException $e)

{
$output = ' .';
include 'output.html.p h p ';
exit();

}
, ,
.
PDO.
PD O
. t r y c a t c h
, . ,
, PDO
,
. PD O PD O E xception

95

, ,
PD O setAt tribute (chapter4/connect/index.php, ).
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

, , ,
ENT_QUOTES, h t m l s p e c i a l c h a r s
3. PDO: : :
,
PDO. , ,
, ( PDO: : ATTR_ERRMODE),
( PDO: :ERRMODE_EXCEPTION)

. 3 ,
UTF-8 ,
. MySQL -
ISO-8859-1 ( L atin-1). ,
, PD O UTF-8.
,
MySQL. SQL-
SET NAMES " ut f 8" exec.
PDO, $pdo,
(chapter4/connect/index.php, ).
$pdo->exec('SET NAMES "utf8"');

- exec (
, M ySQ L- , ),
,
PDOException. ,
try, PDO. ,
MySQL
(chapter4 /connect /index.php, ).
<?php
try

{
$pdo = new PDO('mysql:host=localhost;dbname=ijdb', 'ijdbuser',
'm y p a s s w o r d ') ;
$pdo->setAttribute(PDO::ATTR_ERRMODE
$pdo->exec('SET NAMES "utf8"');

PDO::ERRMODE_EXCEPTION)?

}
catch (PDOException $e)

{
$output = ' .';
include 'output.html.php';
exit();

}
1 PDO
PHP(http://php.net/manual/ru/pdo.error-handling.php).

96

MySQL

, ,
, . ,
( c h a p t e r 4 / c o n n e c t / i n d e x . p h p ) .
<?php
try

{
$pdo = new PDO('mysql:host=localhost;dbname=ijdb', 'ijdbuser',
'm y p a s s w o r d ') ;
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');

}
catch (PDOException $e)

{
$output = ' .';
include 'output.html.p h p ';
exit();

}
$output = ' .';
include 'output.html.p h p ';

. index.php
output.html.php connect -, URL
http://localhost/connect/. ,
,
(. 4.6).
----LELL

- Mozilla Firefox

0 localhost/connect/

.1__

. 4.6.

MySQL-
, , ,
. 4.7. ,
, .

97

. 4.7.

.
? ?
, . c a tc h ,
( c h a p t e r 4 / c o n n e c t / i n d e x . p h p , ).
catch (PDOException $)

{
$output = ' .1;
include 'output.html.p h p 1;
exit();

}
,
. .
catch, ,
PDOException,
$. ,
.
. PDO,
$pdo PDOException
. , ,
, .
catch (PDOException $)

{
$output = ' :
$->getMessage();
include 'output.html.p h p ';
exit();

' .

}
g e tM e s s a g e , $,
,

98

MySQL

(.). , P H P - ,
, . 4.8.
- Mozilla Firefox

----------------

_
9 localhost/connect/______________________________

"7

&

: SQLSTATEfHYOOO]
[1045] Access denied for user iid b u se r^ localhost' (using password: YES)

. 4.8. ,

,
(. 4.9).
- Mozilla Firefox
_____
localhost/connect/

.......

: SQLSTATE[42000]:
Syntax error or access violation: 1115 Unknown character set: 'utf9'

. 4.9. ,


(, ),
. ,

.
,
, .

99


, , , MySQL
, .
, PDO.
, , null.
$pdo = null; //

, , ,
, .

SQL-
2 MySQL,
phpMyAdmin. SQL- ()
. PD O .
$pdo->exec( )

,
.
, SET NAMES "ut f 8",
.
, (
, ),
PDOException, .
joke 2 (chapt 4 /
createtable/index.php, ).
try

{
$sql = 'CREATE TABLE joke (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
joketext TEXT,
jokedate DATE NOT NULL
) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB';
$pdo->exec($sql);

}
catch (PDOException $e)

{
$output = ' joke:
include 'output.html.p h p ';
exit();

' . $e->getMessage();

}
$output = ' joke .';
include 'output.html.p h p ';

,
try - catch.
getMessage, MySQL

100

MySQL

. . 4.10 ,
, j .
- Mozilla Firefox

joke: SQLSTATE[42S01]: Base table or


view already exists: 1050 Table joke* already exists

. 4.10. CREATE TABLE ,


DELETE, INSERT UPDATE,
, ,
(), . (
2)
( c h a p t e r 4 / u p d a t e c h i c k e n / i n d e x . p h p , ).
try

{
$sql = 'UPDATE joke SET jokedate="2012-04-01"
WHERE joketext LIKE "%%"';
$affectedRows = $pdo->exec($sql);

}
catch (PDOException $e)

{
$output = ' :
include 'output.html.p h p ';
exit();

' . $e->getMessage();

}
$ a f fe c ted R o w s , ,
, ( c h a p t 4 /
u p d a t e c h i c k e n / i n d e x . php, ).
$output = " : $affectedRows";
include 'output.html.p h p ';

. 4.11 (,
).
,
(. 4.12). ,
, , .

101

- Mozilla Firefox

I |

_____

3/

localhost/updatechicken/

: 1

. 4.11.

- Mozilla Firefox
_

[ cd foi

localhost/updatechicken/

__ -_______ ;__i____

. 4.12. MySQL ,

SELECT .
,
.


SELECT
SQ L-:
, ,
( ). SELECT
. , ,
. , SELECT

102

MySQL

, ,
, .
query ,
SQL-, . ,
PDOStatement,
, , (),
(chapt4 /1 ist jokes /index.php, ).
try

{
$sql = 'SELECT joketext FROM joke';
$result = $pdo->query($sql);

}
catch (PDOException $e)

{
$error = ' :
include 'error.html.php';
exit();

' . $e->getMessage();

}
, (chapt4/
list jokes /error .html .php).
<!DOCTYPE html>
<html lang="en">
<head>
cmeta charset= "utf-8">
<title>Omn6Ka CKpnnTa</title>

</head>
<body>
<P>
<?php echo $error; ?>
</p>
</body>
</html>

,
( PDOStatement) $result.
, j.

, .
3 ,
while.
.
while ($row = $result->fetch())

{
:

}
, ,
, . .
$row = $result->fetch();

103

f e t c h P D O S ta te m en t
( 3).
, f a l s e 1.
$row ,
.
w h ile .
, f a l s e ,
. $row
.
.
, f e t c h ,
,
. $row ,
$row [ ' j t e x t ' ] j t e x t .
P H P -,
.
$ j o k e s ( c h a p t e r 4 / 1 i s t j o k e s / i n d e x . php, ).
while ($row = $result->fetch())

{
$jokes[]

= $ r o w ['joketext'];

}
jokes.html.php
.
,
( c h a p t e r 4 / l i s t j o k e s / i n d e x , php).
<?php
try

{
$pdo = new PDO('mysql:host=localhost;dbname=ijdb', 'ijdbuser',
'mypassword');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.php';
exit();

}
try

{
$sql = 'SELECT joketext FROM joke';
$result = $pdo->query($sql);

}
catch (PDOException $e)
1 , P D O : fetch
, .
PDOException,
while.

104

MySQL

{
$ = ' :
include 'error.html.php';
exit();

' . $e->getMessage();

}
while ($row = $result->fetch())

{
$jokes[] = $row['joketext1];

}
include 'jokes.html.php1;

jokes.html.php.
, .
,
w h i l e f o r .
f o r e a c h .
foreach ( as $item)

{
: $ i t e m

}
f o r e a c h
, a s ,
.
, , ,
.
f o r e a c h
. $ j o k e s .
<?php
foreach ($jokes as $joke)

{
?>
: HTML- $ j o k e
<?php

}
?>
P H P -, , H T M L -,
, ,
f o r e a c h .
foreach (array as $item):
: $item
endforeach;

.
<?php foreach ($jokes as $joke): ?>
: HTML- $joke
<?php endforeach; ?>

,
( c h a p t e r 4 / l i s t j o k e s / j o k e s .h t m l .p h p ).
b lo c k q u o t e .

105

4
<!DOCTYPE html>
chtml larig="en">
<head>
<meta charset= "utf-8">
<title>CnncoK myTOK</title>

</head>
<body>
<> , :</>
<?php foreach ($jokes as $joke): ?>
<blockquote>
< p x ? p h p echo htmlspecialchars($joke, ENT_QUOTES, 'UTF-8');

?>
</p>
</blockquote>
<?php endforeach; ?>
</body>
</html>

, .
,
HTML. , <, > & &lt;, &gt; &amp;
. h t m l s p e c i a l c h a r s .
. 4.13 , ,
.
-Mozilla Firefox

:...

S ~ ]

( <J>) localhosthstjakei

('5

, :
?
!
" - , - , ...1, , , '
.

.":

-----

.. ........... - ;

. 4.13.

FOREACH
________

PD O S tatem en t w h i l e ( c h a p t e r 4 /
l i s t j o k e s / i n d e x , php, ).
while

($row = $ r e s u l t - > f e t c h ())

{
$jokes[]

106

= $ r o w ['j o k e t e x t '];

MySQL

, PDOStatement, foreach,
. , while foreach,
.
foreach ($result as $row)

{
$jokes[] = $row['joketext1];

}

.


,
.
, , . ,
( c h a p t e r 4 / a d d j / f o r m .h tm l .p h p ).
< IDOCTYPE html>
chtml lang="en">
<head>
<meta charset="utf-8">

<title>flo6aBneHne myTKH</title>
<style type="text/css">
textarea {
display: block;
width: 100%;

}
</style>
</head>
<body>
<form action="?" method="post">
<div>
clabel for="joketext"> :</label>
<textarea id="joketext" name="joketext" rows="3" cols="40">
</textarea>
</div>
<divxinput type =" submit" value="11></div>
</form>
</body>
</html>

,
, index.php ( ).
, a c t i o n ,
?. , URL,
, .
a c t i o n ,
.

107

(. 4.14).
- Mozilla Firefox

:X:

<> . localhost/addjoke/?addjoke

V <?

W -------------------

(@v

:
, ,
.)

"- - |'"' ^ ....... .<* " ' ' ' - ....""""y - g------ ----------------

. 4.14.
j o k e t e x t ,
, .
$_PO ST $_REQUEST, .
,
. ,
( c h a p t e r 4 / a d d j o k e / j o k e s .h tm l .p h p , ).
<body>
< p x a href="?addjoke"> <//>
<p> , :</>

, -,
, ? ad d j ,
, .
,
.
( c h a p t 4 / ad d j / i n d e x . php,
).
if (isset($_GET['addjoke']))

{
include 'form.html.php1;
exit();

}
i f ,
a d d j , .
(? a d d j ) a d d j ,
. i s s e t ( $_GET [ 1a d d j o k e ' ] )
.
form.html.php. e x i t .

108

MySQL

,
. , ,
$_POST [ ' j o k e t e x t 1] ( c h a p t e r 4 / a d d j o k e / i n d e x , php, ).
if (isset($_POST['joketext']))

{
,
INSERT, j o k e t e x t ,
$_POST[ 1j o k e t e x t 1].
$sql = 'INSERT INTO joke SET
joketext="' . $_POST['joketext'] . 1",
jokedate="today's date"';
$pdo->exec($sql);

:
$_POST[ ' j o k e t e x t ' ] ,
. SQ L-,
MySQL. SQL-.

1.

SQ L-.
.

( \ ) ,
, , SQL-.
. -,
, ,
. ,
,
. -,
SQL-, - ,
. 3,
:
, .
, ,
,
. , ,
. ,
-,
, 2.
1 SQL-
, . ,
,
(http://www.gizmodo.com.au/2010/03/sql-injection-license-plate-hopes-to-foil-euro-traffic-cameras/).
2 -
, magic_quotes_gpc, php.ini,
Off. , .
, .

109

1 ,
( c h a p t e r 4 / a d d j / i n d e x . php, ).
if (get_magic_quotes_gpc())

{
$process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
while (list($key, $val) = each($process))

{
foreach ($val as $k => $v)

{
unset($process[$key][$k]);
if (is_array($v))

{
$process[$key][stripslashes($k)] = $v;
$process[] = &$process[$key][stripslashes($k)];

}
e lse

{
$process[$key][stripslashes($k)] = stripslashes($v);

}
}
}
unset($process);

}
He .
, , ,
.
-,
, (
9). ,
2.
, ,

, .
SQ L-,
,
( ).
, ,
.
PD O
.
INSERT
$_PO ST [ ' j t e x t ' ] .
$sql = INSERT INTO joke SET
joketext = :joketext,
jokedate = " ' ;

1http://www.php.net/manual/en/security.magicquotes.disabling.php.
2 6 , .

110

MySQL

$s = $ p d o -> p r e p a r e ($ sq l);
$ s-> b in d V alu e( ' : j o k e t e x t ' , $_POST[ ' j o k e t e x t ' ] ) ;
$ s -> e x e c u te ();

. SQL-
, , $ s q l.
INSERT - : joketext,
: j oket ext. j okedat
.
PD O ($pdo) prepare,
SQL-.
MySQL, .
MySQL
joket ext . prepare PDOStatement ( ,
SELECT)
$s.
, M ySQL- ,
( ), bindValue
PDOStatement ( $ s ).
( ).
$_POST [ ' j oket e x t ' ] ,
' : joket e x t ', . MySQL ,
, SQL-. ,
,
SQL. ,
, SQL-.
PDOStatement execute,
MySQL ,
1.
, j o k e d a t .
, - ,
MySQL (YYYY-MM-DD).
: CURDATE.
$ sq l = 'INSERT INTO jok e SET
jo k e te x t = : j o k e t e x t ,
jo k ed a te = CURDATE( ) ' ;
$s = $ p d o -> p r e p a r e ($ sq l);
$ s-> b in d V a lu e( ' : j o k e t e x t ', $_POST[ ' j o k e t e x t ' ] ) ;
$ s - > e x e c u te ();

CURDATE, MySQL,
j o k e d a t . MySQL
,
. , ,
.
1 PDOStatement
e x e c u te . ,
.

ill

, , i f ,
, ( c h a p t e r 4 / a d d j / in d e x .p h p ,
).
if (isset($_POST[1joketext']))

{
try

{
$sql = 'INSERT INTO joke SET
joketext = :joketext,
jokedate = CURDATE()';
$s = $pdo->prepare($sql);
$s->bindValue(':joketext', $_POST['joketext']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' :
include 'error.html.p h p ';
exit();

' . $e->getMessage();

}
header('Location:
exit();

}
i f .
, ,
,
. ,
.
, ,

jokes.html.php.
,
. - ,
,
, .
,
-
.
HTTP - 1,
: , , .
h e a d e r
, , ,
. ,
L o c a t i o n , .
header('Location: URL ');

i HTTP HypertextTransferProtocol,
. ,
- .

112

MySQL

(
). , ,
.
index.php, ( ),
.
,
( c h a p t e r 4 / a d d j o k e /
i n d e x . php, ).
header('Location: .1);
exit();

$_SERVER[ PHP__SELF ] - URL ____________



$ _ s e r v e r [ 1p h p _ s e l f ] . $ _ g e t , $ _ p o s t $ _ r e q u e s t ,
,
. ,
. , PHP-,
- .
, http://localhost/addjoke/
http://localhost/addjoke/index.php, $ _ s e r v e r [ ' p h p _ s e l f ' ]
URL.
.
$ _ s e r v e r [ ' p h p _ s e l f ' ] . ,
, ,
, .

, ,
. ( c h a p t e r 4 / a d d j o k e / i n d e x . p h p ) .
<?php
if (get_magic_quotes_gpc())

{
$process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
while (list($key, $val) = each($process))

{
foreach ($val as $k => $v)

{
u n s e t ($process[$key][$k]);
if (is_array($v))

{
$process[$key][stripslashes($k)] = $v;
$process[] = &$process[$key][stripslashes($k)];

}
else

{
$process[$key][stripslashes($k)] = stripslashes($v);

}
>
}
unset($process);

113

if (isset($_GET['addjoke']))

{
include 'form.html.p h p ';
exit()?

}
try

{
$pdo = new PDO('mysql:host=localhost;dbname=ijdb', 'ijdbuser',
'mypassword');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"')?

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();

if (isset($_POST['joketext']))

{
try

{
$sql = 'INSERT INTO joke SET
joketext = :joketext,
jokedate = CURDATEO';
$s = $pdo->prepare($sql);
$s->bindValue(':joketext', $_POST['joketext']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' :
include 'error.html.php';
exit();

' . $e->getMessage();

}
h e a d e r ( 1Location: .1);
e x i t ();

}
try

{
$sql = 'SELECT joketext FROM joke';
$result = $pdo->query($sql);

}
catch (PDOException $e)

{
$error = ' :
include 'error.html.p h p ';
exit();

while ($row = $result->fetch())

114

' . $e->getMessage();

MySQL

$jokes[]

include

= $ r o w ['joketext

'jokes.html.php';

, , ,
, .
PD O .
, ,
,
.

(. 4.15).
- Mozilla Firefox

__________________________
#

localhost/addjoke/

v e Ob

I t t If

, :
?
!
" - , - ,
- ...", ,
, .
, ,
.
, ?
. 4.15. SQL!

. index.php,
, MySQL
, .


:
. ,
, .
,
.
,
4. .

115

-
index.php.
DELETE SQL,
2.
,
.
, i d j .
.
, , ,
, , .
SELECT,
.
, j o k e t e x t , i d ( c h a p t e r 4 / d e l e t e j o k e /
i n d e x . php, ).
try

{
$sql = 'SELECT id , joketext FROM joke';
$result = $pdo->query($sql);

}
catch (PDOException $e)

{
$error = ' :
include 'error.html.php';
exit();

' . $e->getMessage();

}
w h i l e ,
$ j o k e s .
, . $ j o k e s
( c h a p t e r 4 / d e l e t e j o k e / i n d e x . p h p , ).
while ($row = $result->fetch())

{
$jokes[] = array('id' => $row['id']/ 'text' => $row['joketext'])?

}
FOREACH
g ig

,
foreach.
foreach ($result as $row)

{
$jokes[]

= array('id'

=> $row['id'],

'text' =>

$row['joketext']);

}
w h i l e $ j o k e s ,

. , $ j o k e s []
i d ( $ j o k e s [n] [ ' i d 1] ) j o k e t e x t ( $ j o k e s [n] [ ' t e x t ' ] ).

116

MySQL

jokes.html.php. ,

( c h a p t e r 4 / d e l e t e j / j o k e s . h t m l . php,
).
<?php foreach

($jokes as $joke): ?>

<form action="?deletejoke" methods"post">

<blockquote>

<P>
<?php echo htmlspecialchars($joke['text'], ENT_QUOTES, 'UTF-8');

i>
<input types"hidden" names"id" values"<?php
echo $joke['id']; ?>">
<input types"submit" valuesyflannTb">
</p>
</blockquote>
</form>
<?php endforeach; ?>

.
1. , ,
. ? d e l e t j
a c t i o n .
2. $ j o k e s ,
. ,
. $ j o k e $ j o k e [ ' t e x t ' ].
3.
. id .
, ( c i n p u t ty p e = " h id d e n " >).
i d ,
($ j o k e [ 1i d ' ] ).
4. ,
h t m l s p e c i a l c h a r s ,
HTML.
, ,
i d MySQL, .
5. < i n p u t t y p e = " s u b m i t " > .
v a lu e .
6. .
_____________________________________________
HTML, , , , input
blockquote,
(). :
blockquote,
. ,
, (Cascading
Style Sheets, CSS), .

117


CSS MySQL.
,
CSS , .
HTML-,
CSS, .

. 4.16 .
I

{<$ 1 0

.....

________ ;________
localhost'deletejoke/

j p i | ^

v----1

- Mozilla Firefox

"

-- -

,,


, :
?
!

" - , - , ...", , ,
.
, ,
.

_zzzn

. 4.16.

, , .
,
( c h a p t e r 4 / d e l e t e j / i n d e x . php, ).
if (isset($_GET['deletejoke']))

{
try

{
$sql = 'DELETE FROM joke WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id ', $_POST[id']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' :
include 'error.html.p h p ';
exit();

}
header('Location: . ') ;
exit();

118

' . $e->getMessage();

MySQL

,
.
DELETE 1.
$_PO ST [ 1i d ' ]
. h e a d e r
.

?_______________________________________________
,
, , .
HTML-
. , .
<?php foreach ($jokes as $joke): ?>
<blockquote>
<P>
<?php echo htmlspecialchars($joke['text'], ENT_QUOTES,
'UTF-8'); ?>
<a href="?deletejoke&amp;id=<?php echo $joke['id'];
? >"> </a >
</p>
</blockquote>
<?php endforeach; ?>

-
(, ).
.
m e th o d = " g e t ":
, .
,
m e th o d = " p o s t".
,
method= " p o s t " -. ,
, , , ,
.
m ethod= " g e t " .
(
)
,
, .
, .

( c h a p t e r 4 / d e l e t e j /
i n d e x . p h p ) . SiteP oint
(http://www.sitepoint.com/forums/).
1 , , ,
SQL-,
, . (
) . ,
,
. : ,
.

119

4
<?php
if (get_magic_quotes_gpc())

{
$process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
while (list($key/ $val) = each($process))

{
foreach ($val as $k => $v)

{
unset($process[$key][$k]);
if (is_array($v))

{
$process[$key][stripslashes($k)] = $v;
$process[] = &$process[$key][stripslashes($k)];

}
else

{
$process[$key][stripslashes($k)] = stripslashes($v);

}
}
}
unset($process);

if (isset($_GET['addjoke1]))

{
include 'form.html.php';
exit();

}
try

{
$pdo = new PDO('mysql:host=localhost;dbname=ijdb1, 'ijdbuser',
'mypassword');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');

}
catch (PDOException $e)

{
$error = ' .';
include 'e r r o r .h t m l .p h p ';
e x i t ();

if (isset($_POST['joketext']))

{
try

{
$sql = 'INSERT INTO joke SET
joketext = :joketext,
jokedate = CURDATE()';
$s = $pdo->prepare($sql);
$s->bindValue(':joketext', $_POST['joketext']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' :

120

' . $e->getMessage();

MySQL
include 1error.html.p h p ';
exit();

}
header('Location:
exit();

}
if (isset($_GET['deletejoke']))

{
try

{
$sql = 'DELETE FROM joke WHERE id = rid';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' :
include 'error.html.p h p ';
exit();

' . $e->getMessage();

}
header('Location: .');
exit();

}
try

{
$sql = 'SELECT id, joketext FROM joke';
$result = $pdo->query($sql);

}
catch (PDOException $e)

{
$error = ' :
include 'error.html.p h p ';
exit();

' . $e->getMessage();

}
while ($row = $result->fetch())

{
$jokes[] = array('id' => $row['id'],

'text' => $row['joketext']);

}
include 'jokes.html.php';


P D O , (PDO,
PDOException PDOStatement).
,
M ySQL -
, .

121

PD O MySQL,
i j db,
.
,
: . ,
.
.
5 phpMy Admin
,
SQL- .

2
, j .
MySQL,
.

M ySQL,
.
, .
,
,
. ,
, .

SQL Simply SQL (ht^://www.sitepoint.(^m/books/
sqM/). ,
, Database in Depth (Sebastopol: O Reilly, 2005; http://oreilly.
com/catalog/9780596100124/).


j . ,
, ( i d ) ,
( j o k e t e x t ) ( j o k e d a t e ) .
SQL-
( c h a p t e r 5 / s q l / j o k e s l . s q l ) 1.
# joke.
CREATE TABLE joke (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
joketext TEXT,

1 ,
phpMyAdmin, ij d b
SQL-. phpMyAdmin
. .sql,
,
.

123

5
jokedate DATE NOT NULL
) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB;
# .
INSERT INTO joke SET
joketext = ' ?
!',
jokedate = '2009-04-01';
INSERT INTO joke
(joketext, jokedate) VALUES (
'" - , - , - ..." , , '' .',
"2009-04-01"

);
, - ,
, . ,
, j . SQL
ALTER TABLE.
phpMyAdmin (. 2), (
, , i j d b )
.
ALTER TABLE joke ADD COLUMN authorname VARCHAR(255)

a u th o rn a m e .
VARCHAR ( 2 5 5 ) 255 ,
, .
.
ALTER TABLE .
ALTER TABLE joke ADD COLUMN authoremail VARCHAR(255)

, ,
MySQL 1.
DESCRIBE joke

, . 5.1.
, ? ,
HTML- P H P - 4
,
UPDATE. ,
: ? ,
.
1 DESCRIBE , phpMy Admin
j .
, .

124

AUTO INCREMENT

jokedate

date

authoremail varehar(255)

NULL

. 5.1. j



, ,
, . ,
, , ,
. ,
, .
,
.
, ,
? , ,
.
, ,
. ,
, .
,
.
.
,
, -
. .
SELECT DISTINCT authorname, authoremail
FROM joke

D ISTIN CT . ,
20 ,
, 20.
- ,
, , ,
, .
.

-,
, .

125

: ,
. , .
, , ... , .
,
.

.
j , .
i d ,
. j ,
, .
. 5.2.

id

joketext

jo k e f t .............................
jokedate
authorid

...

2012-04-01

- ...

2012-04-01

...

2012-05-16

Z7

'

thatguy@kevinyank.com
_____

2 1

nrm-mr,

____ _________ __________________

joan@example.com

. 5.2. a u t h o r i d a u t h o r
j
,
. a u t h o r i d j o k e
, , 1
2, 3. :
,
, .

( ),
.
: ( ),

.
:
CREATE TABLE.

126

,
ALTER TABLE. j
.
ALTER TABLE joke DROP COLUMN authorname
ALTER TABLE joke DROP COLUMN authoremail

.
CREATE TABLE author (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
email VARCHAR(255)
) DEFAULT CHARACTER SET utf8 ENGINE^InnoDB

j o k e a u t h o r i d .
ALTER TABLE joke ADD COLUMN authorid INT

, CREATE TABLE,
( c h a p t e r 5 / s q l / 2 t a b l e s . s q l , ).
# joke,
# .
CREATE TABLE joke (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
joketext TEXT,
jokedate DATE NOT NULL,
authorid INT
) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB;
# author.
CREATE TABLE author ( *
id INT NOT NULL AUT6_INCREMENT PRIMARY KEY,
name VARCHAR(255),
email VARCHAR(255)
) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB;


, a u t h o r i d 1.
INSERT UPDATE, .
, INSERT,
( c h a p t e r 5 / s q l / 2 t a b l e s . s q l , ).
# .
# ,
# .
INSERT INTO author SET

1 . : 7 ,

, .

127

= ' ',
email = 'thatguy@kevinyank.com';
INSERT INTO author (id, name, email)
VALUES (2, ' ', 'joan@example.com');
# .
INSERT INTO joke SET
joketext = ' ?
!',
jokedate = '2012-04-01',
authorid - 1;
INSERT INTO joke (joketext, jokedate, authorid)
VALUES (
'" - , - , - ..." , , \' .',
'2012-04-01',
1

);
INSERT INTO joke (joketext, jokedate, authorid)
VALUES (
' , ,
."',
2012-04-01',
2

);


, , ,
. ,
.
, P H P -
SELECT.
try

{
$sql = 'SELECT joketext, authorname, authoremail FROM joke';
$result = $pdo->query($sql);

}
catch (PDOException $e)

{
$error = ' :
include 'error.html.p h p ';
exit();

}
foreach ($result as $row)

{
$jokes[] = array(
'id' => $row['id'],
'text' => $row['joketext'],
'name' => $row['authorname'],
'email' => $row['authoremail']

128

);

' . $e->getMessage();


. j ,
.
q u e ry PDO.
,
.
, ,
, . ,
, MySQL, ,
. JO IN () SELECT
.
, .
.
SELECT
FROM 1 INNER JOIN 2
ON ()

i d j o k e t e x t
jo k e , name e m a il a u t h o r .
, a u t h o r i d ( j )
i d ( a u th o r ) .

. . 5.3
5.4 .
SELECT id, LEFT(joketext, 20), authorid FROM joke

" -

. 5.3. j

SELECT * FROM author

id name

email

1j

j thatguy@kevinyank.com

2 1 ; joan@exampie.com

. 5.4. author

JOIN.
. 5.5.
SELECT joke.id, LEFT(joketext, 20), name, email

129

5
FROM joke INNER JOIN author
ON authorid = author.id

I thatguy@kevlnyank.com

! joan@examplexom

. 5.5.


, .
,
.
: i d , ,
,
. j o k e a u t h o r
j . i d a u t h o r . id . , MySQL ,
i d , (. 5.6).
SELECT id, LEFT(joketext, 20), name, email
FROM joke INNER JOIN author
ON authorid = id

. 5.6. MySQL

,
, ,
JOIN (chapt 5/ jokes /index, php, ).
try

{
$sql = 'SELECT joke.id, joketext, name, email
FROM joke INNER JOIN author
ON authorid = author.id';
$result = $pdo->query($sql);

}
catch (PDOException $e)

{
$error = ' :
include 'error.html.p h p ';
exit();

}
foreach ($result as $row)

{
$jokes[] = array(
'id' => $row['id],
'text' => $row['joketext'],
'name' => $row['name'],
'email' => $row['email']

130
\

' . $e->getMessage();

);
include 'jokes.html.p h p ';

,
( c h a p t e r 5 / j o k e s / j o k e s .h t m l .p h p ,
).
<?php foreach ($jokes as $joke): ?>
<form action="?deletejoke" method="post">
<blockquote>
<P>
<?php echo htmlspecialchars($joke['text'], ENT_QUOTES, 'UTF-8');

?>
cinput type="hidden" name="id" value="<?php echo $joke['id'];

?>">
<input type="submit" value="">
( <a href="mailto:<?php
echo htmlspecialchars($joke['email'], ENT_QUOTES,
UTF-8'); ?>"><?php
echo htmlspecialchars($joke['name'], ENT_QUOTES,
'UTF-8'); ?></a>)
</p>
</blockquote>
</form>
<?php endforeach; ?>

(. 5.7).
) -Mozilla Firefox
(3) localhost/jokes/

00

'=


, :
?
! [ ( )
" - , - , ...", , , '
. ( )
, ,
. [ ( )

. 5.7. ,
,
,
. ,
, .

131

5
SELECT joketext
FROM joke INNER JOIN author
ON authorid = author.id
WHERE name = " "

(. 5.8)
joke, JOIN.
, author.
, ,
JOIN .
.

, , ...

. 5.8.



, .
,
.
.

j.
,
1.
,
. ,
. ,
. ,
,
.
i d (
), .
.
. ,
, (
). , ,
, .
()
(). , ,
.
1 . ,
, SELECT,
.
.

132

, , ()
().
, , ,
,
(. 5.9).

Kevin Yank

thatguy@kevinyank.com,
kyank@example.com

Joan Sm ith

joan@example.com,
jsmith@example.com

. 5.9.
. ,
, (
, ),
. P H P - ! ,
e m a i l ,
, .
,
,
. , :
(
) (. 5.10).

thatguy@kevinyank.com

kyank@example.com

joan@example.com

jsmith@example.com

Joan Smith

. 5.10. a u t h o r id e m a il a u th o r

JOIN,
, .
SELECT email
FROM author INNER JOIN email
ON authorid = author.id
WHERE name = " "


, ,
. ,
.
. - .
, :
', , ,
. , ,
, .
CREATE TABLE category (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255)
) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB

:
. ,
, , ', .
,
. .
,
. , j
category,
, .
: , ,
, .

.
, . . 5.11 ,
, .
jokecategory jokeid
cat egory id. ,
...
.
.
. ,
, id. PRIMARY KEY (
). MySQL ,
.

134


...

...

. 5.11. j o k e c a t e g o r y
j c a t e g o r y

.
.

. . ,
, ,
, .
.
CREATE TABLE jokecategory (
jokeid INT NOT NULL,
categoryid INT NOT NULL,
PRIMARY KEY (jokeid, categoryid)
) DEFAULT CHARACTER SET Utf8 ENGINE=InnoDB

,
j o k e i d c a t e g o r y i d .
,
,
1.
,
, JOIN,
,
'.
SELECT joketext
FROM joke INNER JOIN jokecategory
ON joke.id = jokeid
INNER JOIN category
ON categoryid = category.id
WHERE name = " '"

, JOIN.
j j o k e c a t e g o ry ,
c a t e g o r y .
, .
1 j o k e c a t e g o r y
, CREATE TABLE INSERT ( ,
).

135

, ,
.
SELECT name
FROM joke INNER JOIN jokecategory
ON joke.id = jokeid
INNER JOIN category
ON categoryid = category.id
WHERE joketext LIKE ^

, a u t h o r
, ,
'.
SELECT author.name
FROM joke INNER JOIN author
ON authorid = author.id
INNER JOIN jokecategory
ON joke.id = jokeid
INNER JOIN category
ON categoryid = category.id
WHERE category.name = '

,

. , MySQL
.
,
, .

SQL-. , , SELECT
.
, , ,
,
4 .
7.
.
.
.


, P H P -. ,
.
, . 3
: .
- H TM L-,
. i n c l u d e .
, .
, , -
, 4. ,
( ) 1,
.
.
,
.
( , ,
).


, ,
.
i n c l u d e . ,

.
( ) ,
P H P -,
.

HTML-
.
, ( - ,
1 , PHP- WordPress
.

137

25 ), , , Server Side
Includes (SSI) .
-, SSI
HTML, JavaScript CSS ,
.
P H P - ,
, HTML. ,
.
HTML.
, . ,
,
( c h a p t e r 6 / s t a t i c - f o o t e r / f o o t e r . i n c ..htm l .p h p ).
<div id="footer">
&; 1998&ndash;2012
. .
</div>

.
, .
, .inc.html.php.
(chapter6/static-footer/
samplepage.html.php).
< IDOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>npHMep CTpaHHUbi</title>
</head>
<body>
<p id="main">

.
</>
<?php include 'footer.inc.html.php'; ?>
</body>
</html>

, ( c h a p t e r /
s t a t i c - f o o t e r / i n d e x , php).
<?php
include 'samplepage.html.php';

?>
(. 6.1).
,
footer.inc.html.php.
, !
,
( c h a p t e r 6 / d y n a m i c - f o o t e r / f o o te r . in c .h tm l.p h p ) .

138


<div id="footer">
- &;
1998&ndash; <?php echo date('Y'); ?> .
.
</div>

- Mozilla Firefox

___
localhost/static-footer/


.
- > 1998-2012
. .

. 6.1.

-
, ,
,
. ,
.
try

{
$pdo = new PDO('mysql:host=localhost;dbname=ijdb', 'ijdbuser',
'm y p a s s w o r d ');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');

}
catch (PDOException $e)

{
$error = 'He .';
include 'error.html.php';
exit();

}
, 12 ,
, . P H P -
, (,
t r y c a t c h ) . .

139

,
.
.
, -
. ,
, .
, .
. 6.2 ,
. ,
, ,
-.

, .
db.inc.php1
( c h a p t e r 6 / j o k e s / d b . i n c .p h p ).
index3.php [ \

try

Spdo new PDOfmysql


Spdo->setAttribute{POC I
$pdo->execfSET NAME?

Spdo new PDOfmysql


Spdo->setAttfibute{PDC
Spdo->exeefSET NAME?

catch (PDOException $e)

catch (PDOException $e)

index.

index.php

include 'db.ine.php;

include db.inc.php';

[\

index.php

include db.inc.php*

Spdo - new PDOfmysql


Spdo- >set AttributelPDC
Spdo->execfSFT NAME?
catch {PDOException $e)

. 6.2.
1 (
.inc.php) -. ,
PHP- -
, .
. - .inc. , -
PHP-, .
, , ,

, , .

140


<?php
try

{
$pdo = new PDO('mysql:host=localhost;dbname=ijdb', 'ijdbuser',
'm y p a s s w o r d ');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES nu t f 8 m t ) ;

}
catch (PDOException $e)

{
$error = 'He .';
include 'error.html.p h p ';
exit();

}
, P H P -. ,
, , ,
, . db.inc.php
( c h a p t 6 / j o k e s / i n d e x . php).
<?php
if (get_magic_quotes_gpc())

{
$process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
while (list($key, $val) = each($process))

{
foreach ($val as $k => $v)

{
unset($process[$key][$k]);
if (is_array($v))

{
$process[$key][stripslashes($k)] = $v;
$process[] = &$process[$key][stripslashes($k)];

}
else

{
$process[$key][stripslashes($k)] = stripslashes($v);

}
}
}
unset($process);

'

if (isset($_GET['addjoke]))

{
include 'form.html.php';
exit();

}
if (isset($_POST['joketext']))

{
include 'd b .inc.p h p ';
try

141

{
$sql = 'INSERT INTO joke SET
joketext = :joketext,
jokedate = CURDATE{)';
$s = $pdo->prepare($sql);
$s->bindValue(':joketext1, $_POST['joketext'] ) ;
$s->execute();

}
catch (PDOException $e)

{
$error = ' :
include 'error.html.php';
exit();

' . $e->getMessage();

}
header('Location:
exit();

.');

}
if (isset($_GET['deletejoke']))

{
include 'd b .inc.p h p ';
try

{
$sql = 'DELETE FROM joke WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':i d ', $_POST['id']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' :
include 'error.html.p h p ';
exit();

' . $e->getMessage();

}
header('Location:
exit();

.');

}
include 1d b .inc.p h p ';
try

{
$sql = 'SELECT joke.id, joketext, name, email
FROM joke INNER JOIN author
ON authorid = author.id';
$result = $pdo->query($sql);

}
catch (PDOException $e)

{
$error = ' :
include 'error.html.p h p ';
exit();

142

' . $e->getMessage();

foreach ($result as $row)

{
$jokes[] = array(
'id' => $row['id'],
'text' => $row['joketext'],
'name' => $row['name'],
'email' => $row['email']

);
}
include 'jokes.html.php';

,
, db.inc.php i n c l u d e .

SQL- in c lu d e .

, .
i n c l u d e ,
-.
, .

. .
.


i n c l u d e , ,
, P H P - .
r e q u i r e , i n c l u d e _ o n c e r e q u i r e _ o n c e .
i n c l u d e r e q u i r e . -
, :
, - .
i n c l u d e , ,
r e q u i r e , 1.
,
, r e q u i r e .
i n c l u d e . , , db.inc.php ,
.
,
.

1 , php.ini . , include
,
. require
, .

143

i n c l u d e _ o n c e r e q u i r e _ o n c e
i n c l u d e r e q u i r e . , ,

( ),
. ,
, .
i n c l u d e _ o n c e . 6.3. index.php
categories.inc.php top10.inc.php.
, i n c l u d e _ o n c e
db.inc.php .
db.inc.php top10.inc.php,
categories.inc.php. ,
.
index.php

categories.ir

db.inc.php

<?php

<?php

try
include
categoriesinc.php';
include toplO.inc.php*;

include_once 'db.inc.php

$pdo new PDOfmysql


$pdo->setAttribute(PDC
$pdo->exec(SET NAME5

$categories
$pdo->query($link,...};

}
catch (PDOException $e)

to p 1 0 .in c .p h \
<?php

inc!ude_once db.inc.php;

J | db.inc.php

$jokes
$pdo->query($link,

. 6.3. in c l u d e _ o n c e

i n c l u d e _ o n c e r e q u i r e _ o n c e
(.
).


,
-.
.
, -

144

. db.inc.php
.
, - ,
?
.
W indow s1.
<?php include ':/Program Files/Apache Software Foundation/Apache2.2/
htdocs/includes/db.inc.php'; ?>

Linux-.
<?php include '/usr/local/apache2/htdocs/includes/db.inc.php'; ?>

,
, -.
P H P -
-, .
, ,
, .

, ,
.

-, .
,
. , index.php
http://www.example.com/index.php,
- www. e x a m p l e . com. ,
$_SERVER [ 1DOCUMENT_ROOT' ] -.
4, $_SERVER ,
( $_GET, $_PO ST $_REQUEST).
$_SERVER , ,
$_SERVER [ ' DOCUMENT_ROOT ' ].

Windows, Mac
Linux, Apache IIS2.
<?php include $_SERVER[DOCUMENT_ROOT'] . '/includes/db.inc.php'; ?>

1 (/),
Windows-. ,
, ( \\ ) .
2 $_SERVER [1DOCUMENT_ROOT'] ,
Common Gateway Interface (CGI) .
CGI , -
, . CGI-
. , .
, , , $_
SERVER [ 'DOCUMENT_ROOT ' ] .

145


, (. 4).
( c h a p t e r 6 /
i n c l u d e s / m a g i c q u o t e s . i n c .p h p ).
<?php
if (get_magic_quotes_gpc())

{
$process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
while (list($key, $val) = e a c h ($process))

{
foreach ($val as $k => $v)

{
u n s e t ($process[$key][$k]);
if (is_array($v))

{
$process[$key][stripslashes($k)] = $v;
$process[] = &$process[$key][stripslashes($k)];

}
else

{
$process[$key][stripslashes($k)] = stripslashes($v);

}
}
}
u n s e t ($process);

>

.
<?php
include $_SERVER['DOCUMENT_ROOT'] . '/includes/magicquotes.inc.php';

(
) .
, (db.inc.php magicquotes.inc.php)
includes, -.



. ,
, . .
,
(d a t e )
( i m a g e c r e a t e t r u e c o l o r , http://www.php.net/imagecreatetruecolor).
,
, .
, , ,
-.

146

. ,
, (3) (5).
,
.
$ = 3 * 5 ;

a re a ,
( c h a p t 6 /
c a l c u l a t - / i n d e x . php, ).
$ = (3, 5);

, a r e a ,
( c h a p t e r 6 / c a l c u l a t - / a r e a - f u n c t i o n , i n c .p h p ).
<?php
function area($width/ $height)

{
return $width * $height;

}

a r e a . , < ?php.
, , .
.
function area($width/ $height)

f u n c t i o n ,
, .
( a r e a ) .
, : ,
(_)
, . ,
.
,
.
, , ,
.
. , d a t e
,
.

. $ w id th $ h e ig h t .

, ,
.

{
,
.
({...}).
.
return $width * $height;

.
return.
return
. ,
, .
.
, return
, , .
$width * $height
.
}
.
,
, (chapter6/calculate-area/index.php).
<?php
include_once 'area-function.inc.php';
$area = area(3, 5);
include 'output.html.p h p ';

, ,
,
. .
include_once ( require_once,
).
include
require. ,
.
.
( )
, ,
.

, ,
. geometry.inc.php
.

148


, .

. , .

,
.
,
.
. ,
( ),
, . ,
,
. ,
, .
, ,
.
, , .
$w i d t h
$ w id th ,
. ,
,
.

. ,
db.inc.php ,
$pdo,
, .
,
.
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . /includes/db.inc.php';
function totalJokesO

{
try

{
$result = $pdo->query('SELECT COUNT(*) FROM joke');

}
catch (PDOException $e)

{
$error = ' !1;
include 'error.html.p h p ';
exit();

>
$row = $result->fetch();
return $row[0];

149

,
db.inc.php includes,
. ,
( error.html.php )
includes -.
, db.inc.php.

, $pdo (
) .
, ,
(. 6.4).
http://local host/totaljokes-error/

-------- ---

0 http://local host/totaljokes-error/

Notice: Undefined variable: pdo in


/Users/kyank/DocumentsAorkingcopies/phpmysql5/code/chapter6/tota]jokeserror/totaJjokes-functkm inc.php on line 8
Fatal error: Call to a member function queryQ on a non-object in
^sei^yank/Documents/worklngcopies/phpmysql5/code/chapter6/totaJyokeserror/totaljokes-function inc.php on line 8

. 6.4. t o t a l j o k e s $pdo
, t o t a l j o k e s
$pdo. ,
, .
,
.
( c h a p t e r 6 / t o t a l j o k e s g l o b a l 1 / t o t a l j o k e s - f u n c t i o n . i n c .p h p ).
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php;
function totalJokes()

{
global $pdo;
try

{
$result = $pdo->query('SELECT COUNT(*) FROM joke');

}
catch (PDOException $e)

{
$error = ' !';
include 'e r r o r .html .p h p ';

150


e x i t ();

}
$row = $result->fetch();
return $row[0];

}
g l o b a l , ,
,
( , ).
.
,
.
$GLOBAL S
( c h a p t e r / t o t a l j o k e s - g l o b a l 2 / t o t a l j o k e s - f u n c t i o n . i n c .p h p ) .
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
function totalJokes()

{
try

{
$result = $GLOBALS[1p d o 1]->query(1SELECT C O U N T (*) FROM joke');

}
catch

(PDOException $e)

{
$error = ' I';
include 1error.html.php';
exit () ;

}
$row = $result->fetch();
return $row[0];

}
, $pdo $GLOBALS [ ' p d o 1].
$GLOBALS
, . ,
$ GLOBALS [ 1 1], (
). ,
$pdo.
, : $_SERVER, $_GET, $_POST, $_COOKIE, $ _ F IL E S ,
$_ENV, $_REQUEST $ _ S E S S IO N .
(http://php.net/manual/en/language.variables.superglobals.php).

151

,
, h tm l s p e c i a l c h a r s. 3 ,
h t m l s p e c i a l c h a r s ,
, . ,
.
, ,
( c h a p t e r 6 / j o k e s / j o k e s .h tm l .p h p , ).
<?php echo htmlspecialchars($joke['text'], ENT_QUOTES, 'UTF-8'); ?>

, h t m l s p e c i a l c h a r s ,
, .
HTM L , ( c h a p t e r / i n c l u d e s / h e l p e r s .
i n c . php, ).
<?php
function html($text)

{
return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');

}
h t m l s p e c i a l c h a r s ,
.
<?php echo html($joke['text']); ?>

h tm l o u t ,
( c h a p t e r / i n c l u d e s /
h e l p e r s . i n c . php).
<?php
function html($text)

{
return htmlspecialchars($text, ENT_QUOTES,

'UTF-8');

}
function htmlout($text)

{
echo html($text);

>
,
.
( c h a p t e r 6 / j o k e s h e l p e r s / j o k e s . h t m l . php).
<?php include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/helpers.inc.php'; ?>
<!DOCTYPE html>
chtml lang="en">
<head>
cmeta charset="utf-8">

152


<title>CnncoK myTOK</title>
</head>
<body>
< p x a href=" ?addjoke" > < / / >
<> , :</>
<?php foreach ($jokes as $joke): ?>
<form action="?deletejoke" method="post">
<blockquote>
<P>
<?php h tmlout($j o k e ['t e x t '])/ ?>
<input type="hidden" name="id" value="<?php echo $joke['id'];

?>">
< input type="submit" value= "">
( <a href="mailto:<?php htmlout($jo k e ['ema i l ']); ?>">
<?php htmlout ($joke ['name']); ? x / a > )
</p>
</blockquote>
</form>
<?php endforeach; ?>
</body>
</html>


INCLUDES____________________________
db.inc.php magicquotes.inc.php helpers.inc.php
includes (.
).


, , .
,
db.inc.php magicquotes.inc.php ( c h a p t e r 6 / j o k e s - h e l p e r s /
i n d e x . php).
<?php

include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/magicquotes.inc.php';


if

(isset($_GET{'addjoke']))

{
include 'form.html.php';
e x i t ();

}
if

(isset($_POST['joketext']))

{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
try

{
$sql = 'INSERT INTO joke SET
joketext = :joketext,
jokedate = C U R D A T E O ' ;
$s = $pdo->prepare($sql);

153

6
$s->bindValue(':joketext', $_POST[1joketext1]);
$s->execute();

}
catch (PDOException $e)

{
$error = ' : ' . $e->getMessage() ;
include 'error.html.php1;
exit();

}
header('Location: .');
exit();

}
if (isset($_GET['deletejoke']))

{
include $_SERVER[1DOCUMENTJROOT1] . '/includes/db.inc.php';

try

{
$sql = 'DELETE FROM joke WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' : ' . $e->getMessage();
include 'error.html.php';
exit();

}
header('Location: .');
exit();

}
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';

try

{
$sql = 'SELECT joke.id, joketext, name, email
FROM joke INNER JOIN author
ON authorid = author.id';
$result = $pdo->query($sql);

}
catch (PDOException $e)

{
$error = ' : ' . $e->getMessage();
include 'error.html.php';
exit();

}
foreach ($result as $row)

{
$jokes[] = array(
'id' => $row['id'],
'text' => $row['joketext'],

154


'name' => $row['name'],
'email' => $row['email']

);
}
include 'jokes.html.php';



. ,
,
,
, , ,
,
.
,
. ,
,
. ,
,
,
, .
.
,
- .

(http://www.php.net/oop5).
Master: W rite Cutting-edge
Code (http://www.sitepoint.com/books/phppro1/).
7 ,
( ),
.
,
phpMyAdmin.


-, , ,
,
(C ontent M anagement System, CMS). ,
-, ,
.


SQL-.
4 CMS,
, -,
. ,
, ,
. ,
.
,

SQL-.

, 5.
,
, .

. - ,
P H P -,
. Apache .htaccess,
. .
, .
9.
, CMS.


5
: , (. 7.1). ,
.

156


joke
id

joketext

f t

..............

joke d ate

| 2012-04-01

...

- ...

2012-04-01

...

2012-05-16

a u th o rid

jokecategory
jo k e id

categoryid

I2

thatguy@kcvinyank.com

joan@cxample.com

s category I
id

nam e

. 7.1. ijdb

,
SQL- ( c h a p t e r 7 / s q l / i j d b . s q l ) .
CREATE TABLE joke (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
joketext TEXT,
jokedate DATE NOT NULL,
authorid INT
) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB;
CREATE TABLE author (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
email VARCHAR(255)
) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB;
CREATE TABLE category (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255)
) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB;
CREATE TABLE jokecategory (
jokeid INT NOT NULL,
categoryid INT NOT NULL,

157

7
PRIMARY KEY (jokeid, categoryid)
) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB;
# .
#
# .
INSERT INTO author (id, name, email) VALUES
(1, ' ', 'thatguy@kevinyank.com'),
(2, ' ', 'joan@example.com');
INSERT INTO joke (id, joketext, jokedate, authorid) VALUES
(1, ' ? !',
2012-04-01', 1),
(2, '" - , - , - ..." , , \' .',
'2012-04-01', 1),
(3, ' , ,
.', '2012-04-01', 2),
(4, ' , ? :
, .',
2012-04-01', 2);
INSERT INTO category (id, name) VALUES
(1, ' \ ''),
(2, ' '),
(3, ' '),
(4, ' ');
INSERT INTO jokecategory (jokeid, categoryid) VALUES
(1 , 2 ),
( 2 , 1) ,
(3, 4),
(4, 3);

, CMS
, ,
(. 7.2).
H TM L- ( c h a p t e r 7 / a d m i n / i n d e x . h tm l).
<!DOCTYPE html>
chtml lang="en">
<head>
<meta charset="utf-8">
<title>myT04Han CMS</title>
</head>
<body>
<1> </1>
<ul>
c l i x a href="jokes/"> </></11>
< l i x a href = "authors/"> <//11>
< l i x a href = "categories/"> myTOK</ax/li>
</ul>
</body>
</html>

158

CMS - Mozilia Firefox

localhost/admin/

. 7.2. CMS

: jokes,
authors categories. (index.php)
,
.


authors,
.
,
. ,
, .
,
.
4 ,
, .
, .
, 4.
( c h a p t e r 7 / a d m i n / a u t h o r s / i n d e x . p h p ,
).
// .
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.p h p ';
try

{
$result = $pdo->query('SELECT id, name FROM author');

}
catch (PDOException $e)

{
$error = ' !';

159

7
include 'error.html.p h p ';
exit();

}
foreach ($result as $row)

{
$authors[] = array('id' => $row['id'],

'name' => $row['name']);

}
include 'authors.html.p h p ';

, ,
(db.inc.php)
include .
, ( c h a p t e r 7 /
a d m i n / a u t h o r s / a u t h o r s .h tm l .p h p , ).
<?php include_once $_SERVER['DOCUMENT_ROOT'] .
/includes/helpers.inc.php '; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset= "Utf-8">
<title>YnpaBneHne aBTopaMH</title>
</head>
<body>
<1> </111>
< p x a href ="?add"> <//>
<ul>
<?php foreach ($authors as $author): ?>
<li>
<form action="" method="post">
<div>
<?php htmlout($author['name']); ?>
<input type="hidden" name="id" value="<?php
echo $author['id']; ?>">
<input type="submit" name="action" value="">
<input type="submit" name="action" value="">
</div>
</form>
</li>
<?php endforeach; ?>
</ul>
< p x a href=". ."> <//>
</body>
</html>

.
.
1. , 6,

h t m l s p e c i a l c h a r s .

160

2. , ( ? ad d ) ,
.
3. a c t i o n .
, .
4 ( ? d e l e t j ),
, .
,
.
4. h t m l o u t
.
5. : ,
. name
( a c t i o n ) , ( $_PO ST [ ' a c t i o n '] )
, .
. 7.3 , .

- Mozilla Firefox

localhost/admin/authors/

& *

H
i------------------------------

. 7.3.


,
, ,
.
.
, j
a u th o r id . , ,

161

. ,
.
:
1) ,
;
2) ;
3) , a u t h o r i d
j NULL, , .

.
, MySQL ,
. MySQL
.
10.
, CMS
P H P -,
. (
, , ),
, .
-.
, .
,
, :
. ,
a u t h o r i d (NULL).
, .
,
j o k e c a t e g o r y . , ,
. , ,
, .
, , ,
. ( c h a p t e r 7 /
ad m in / a u t h o r s / i n d e x . php, ).
if (isset($_POST['action']) and $_POST['action'] == '')

{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
// , ,
try

{
$sql = 'SELECT id FROM joke WHERE authorid = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST[1i d ']);
$s->execute();

}
catch (PDOException $e)

162

{
$ = ' , .';
include 'error.html.p h p ';
exit();

$result = $s->fetchAll();
// ,
try

{
$sql = 'DELETE FROM jokecategory WHERE jokeid = :id';
$s = $pdo->prepare($sql);
//
foreach ($result as $row)

{
$jokeid = $row['id'];
$s->bindValue(':id', $jokeid);
$s->execute();

>
>
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();

// , ,
try

{
$sql = 'DELETE FROM joke WHERE authorid = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':i d ', $_POST['id']);
$s->execute();

>
catch (PDOException $e)

{
$error = ' , .';
include 'error.html.p h p ';
exit();

// ,
try

{
$sql = 'DELETE FROM author WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':i d ', $_POST['id ']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();

163

>
header(1Location:
exit();

}
.
.
, ,
if, (chapter7/admin/authors/index.php,
).
if (isset($_POST['action']) and $_POST['action'] == '')

,

. name action,
.
$_POST [' action'], , (
1 ' ).
(chapter7/admin/
authors/index.php, ).
$result = $s->fetchAll();

SELECT,
, .
DELETE ,
. ,
. , .
, SELECT while
foreach,
.
while ($row = $result->fetch())
foreach ($result as $row)


.
.
, .
,
.
SQL- ,
.
.
SELECT , ,
DELETE. ,

164

MySQL
DELETE, SELECT.
, .
fetchAll.
$ s,
$result (chapter7/admin/authors/index.php, ).
$result = $s->fetchAll();

for each,
PDOStatement, . ,
MySQL
.
, (chapter7/admin/authors/
i n d e x . php, ).
// ,
try

{
$sql = 'DELETE FROM jokecategory WHERE jokeid = :id';
$s = $pdo->prepare($sql);
//
foreach ($result as $row)

{
$jokeid = $row['id']?
$s->bindValue(':id'; $jokeId);
$s->execute();

}
}
DELETE,
jokecat egory . ,
foreach, .
( 4 1).
, ,
.
DELETE, .
, MySQL
SQL-
. MySQL SQL ,
DELETE ,
.

1 : ,
,
S Q L -.

165

,
.
SQL-,
. f o r e a c h
, SELECT.
DELETE,
: i d ,
b in d V a lu e .
,
. ,
.
, ,
. phpM yAdmin
,
. ,
.

_______________________________________
.
.
,
.
,
.
.


,
4 .
, .
, ,
.
,
. ,
, ( c h a p t e r 7 / a d m i n / a u t h o r s /
f o r m . h t m l . p h p ).
<?php include_once $_SERVER['DOCUMENT_ROOT'] .
1/includes/helpers.inc.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
cmeta charset="utf-8">
<titlex?php html out ($pageTi tie); ?></title>
</head>
<body>
<h l x?php htmlout ($pageTitle); ?></hl>
<form action="?<?php htmlout($action); ?>" method="post">

166


<div>
<label for="name">HMH: <input type="text" name="name"
id=l,name" value="<?php htmlout($name); ?>"></label>
</div>
<div>
<label for="email"> : cinput type="text"
name="email"
id=11email" value="<?php htmlout ($email); ?>"></label>
</div>
<div>
< input type="hidden" name="id" value="<?php
htmlout($id); ?>">
<input type="submit" value="<?php htmlout($button); ?>">
</div>
</form>
</body>
</html>

:
1) $pageTitle
(<hl>);
2) $act ion ,
;

3) $ n a m e
;
4) $ e m a il
;
5) $id
;
6) $button , .


: . . 7.1 ,
.
7.1.

$pageTitle

' 1

' '

$action

'addform'

'editform'

$name

' ' ( )

$email

' ' ( )

$id

' '( )

id

$button

' '

'
'

167


(chapter7 /admin/authors/
index.php, ).
<?php
include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/magicquotes.inc.php';
if (isset($_GET['add']))

{
$pageTitle = ' ';
$action = 'addform';
$name = '';
$email = '';
$id = " ?
$button = ' ';
include 'form.html.php';
exit();

}
, ,
$_GET[ 'addform' ] (chapter7/admin/authors/
index.php, ).
if (isset($_GET['addform']))

{
include $_SERVER['DOCUMENT_ROOT] . '/includes/db.inc.php';
try

{
$sql = 'INSERT INTO author SET
name = :name,
email = :email';
$s = $pdo->prepare($sql);
$s->bindValue(':name', $_POST['name']);
$s->bindValue(':email', $_POST['email']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.php';
exit();

}
header('Location:
exit();

.');

}
,
,
(chapter7/admin/authors/index.php,
).

168


if (isset($__POST['action']) and $_POST['action'] == '')

{
include $_SERVER['DOCUMENT_ROOT'j . '/includes/db.inc.php';
try

{
$sql = 'SELECT id, name, email FROM author WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id ']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit () ;

}
$row = $s->fetch();
$pageTitle = ' ';
$action = 'editform';
$name = $row['name'];
$email = $row['email'];
$id = $row['id'];
$button = ' ';
include 'form.html.php';
exit();

}
To, ,
$_GET [ 1editform']. ,
, , ,
INSERT UPDATE (chapter7/admin/authors/
index.php, ).
if (isset($_GET['editform']) )

{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
try

{
$sql = 'UPDATE author SET
name = :name,
email = remail
WHERE id = rid';
$s = $pdo->prepare($sql);
$s->bindValue('rid', $_POST['id ']);
$s->bindValue(':name', $_POST['name']);
$s->bindValue(':email', $_POST['email']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';

169

7
exit();

}
header(Location:
exit();

}
. 7.4.
)

LiL _

localhost/admin/authors/


: 0
: molly@faerie.com

.... ...

. 7.4. ,

,
.
, ,
, . ,
.


.

.
, .
.
,
, c a t e g o r y .
, -
, .
, ,

170

>

, ,
. . ,
,
- .
, ,
j o k e c a t e g o r y ( c h a p t e r 7 / a d m i n / c a t e g o r i e s / i n d e x . p h p ,
).
// , ,
try

{
$sql = 'DELETE FROM jokecategory WHERE categoryid = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();

}
// ,
try

{
$sql = 'DELETE FROM category WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();

}

.
( c h a p t e r 7 / a d m i n / c a t e g o r i e s / i n d e x .
php, c h a p t e r 7 / a d m i n / c a t e g o r i e s / c a t e g o r i e s .h t m l .p h p , c h a p t e r 7 /
a d m in /c a te g o r ie s /f o r m .h tm l.p h p c h a p te r 7 /a d m in /c a te g o r ie s /
e r r o r . h t m l . php). db.inc.
php, magicquotes.inc.php helpers.inc.php 6.
<?php
include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/magicquotes.inc.php';
if (isset($_GET['add']))

{
$pageTitle = ' ';

171

7
$action = 'addform';
$name = ' ';
$id = ;
$button = ' ';
include 'form.html.php';
exit();

}
if (isset($_GET['addform']))

{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
try

{
$sql = 'INSERT INTO category SET
name = :name';
$s = $pdo->prepare($sql);
$s->bindValue(':name1, $_POST['name']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();

}
header('Location:
exit();

.');

}
if (isset($_POST['action']) and $_POST['action'] == '')

{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php1;
try

{
$sql = 'SELECT id, name FROM category WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id ']>;
$s->execute();

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();

}
$row = $s->fetch();
$pageTitle = ' ';
$action = 'editform';
$name = $row['name'];
$id = $row['id'];

172


$button = ' ';
include 'form.html.php';
exit();

}
if (isset($_GET['editform']))

{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
try

{
$sql = 'UPDATE category SET
name = :name
WHERE id = :id ';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->bindValue(':name', $_POST['name']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();

}
header('Location: .');
exit();

}
if (isset($_POST['action']) and $_POST['action'] == '')

{
include $__SERVER ['DOCUMENT_ROOT'] . '/includes/db. inc .php';
// , ,
try

{
$sql = 'DELETE FROM jokecategory WHERE categoryid = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id ']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();

}
// ,
try

{
$sql = 'DELETE FROM category WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);

173

7
$s->execute();

}
catch (PDOException $e)

{
$error = , ' .';
include 'error.html.p h p ';
exit();

}
header('Location: .') ;
exit();

}
// .
include $_SERVER['DOCUMENT_ROOT'] . /includes/db.inc.php';
try

{
$result = $pdo->query('SELECT id, name FROM category');

}
catch (PDOException $e)

{
$error = ' !1;
include 'error.html.php';
exit();

foreach ($result as $row)

{
$categories[] = array('id' => $row['id']/ 'name' => $row['name']);

}
I
include 'categories.html.p h p ';
<?php include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/helpers.inc.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>paee aeop</title>
</head>
<body>
<1> </1>
< p x a href =" ?add"> <//>
<ul>
<?php foreach ($categories as $category): ?>
<li>
<form action="" method="post">
<div>
<?php htmlout($category['name']); ?>
<input type="hidden" name="id" value="<?php
echo $category['id']; ?>">
<input type="submit" name="action" value="">
<input type="submit" name="action" value="">
</div>

174


</form>
</li>
<?php endforeach; ?>
</ul>
< p x a href =". ."> <//>
</body>
</html>

<?php include_once $_SERVER['DOCUMENT_ROOT'] .


'/includes/helpers.inc.php'; ?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">

<titlex?php htmlout ($pageTitle) ; ?x/title>


</head>
<body>

<hl x ? p hp htmlout ($pageTitle) ; ? x / h l >


<form action="?<?php htmlout($action); ?>" method="post">
<div>
<label for="name">Ha3BaHne: <input type=''text" name="name"
id="name" value="<?php htmlout($name); ? > " x / l a b e l >
</div>
<div>
< input type="hidden" name="id" value="<?php
h t m l o u t ($id); ?>">
cinput type="submit" value="<?php htmlout($button); ?>">
</div>
</form>
</body>

</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>0mn6Ka CKpnnTa</title>
</head>
<body>

<P>
<?php echo $error;
</p>
</body>
</html>

?>


, ,
.
, , ,
,
. ,

.

175


,
. .
.
, ,
. ,
(chapter7/adm in/jokes/index.
php, ).
// .
include $_SERVER ['DOCUMENT_ROOT'] . '/includes/db. inc .php';
try
$result = $pdo->query('SELECT id, name FROM author');

}
catch (PDOException $e)

{
$error = ' !';
include 'error.html.php';
exit();

foreach ($result as $row)


$authors[] = array('id' => $row['id'],

'name' => $row['name']);

try

{
$result = $pdo->query('SELECT id, name FROM category');

}
catch (PDOException $e)

{
$error = ' !';
include 'error.html.php';
exit();

}
foreach ($result as $row)

{
$categories[] = array('id' => $row['id'],

'name' => $row['name']);

}
include 'searchform.html.php';

$ a u t h o r s $ c a t e g o r i e s ,
searchform.html.php.
( c h a p t e r 7 / a d m i n / j o k e s / s e a r c h f o r m .
h tm l .p h p ).
<?php include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/helpers.inc.php'; ?>
<!DOCTYPE html>

176


<html lang="en">
<head>
<meta charset="utf-8">

<title>YnpaBneHne /t i t l e
</head>
<body>
<1> /
< p x a href =" ?add"> <//>
<form action="" methods"get">
<> , :</>
<div>
clabel for="author"> :</label>
<select name="author" ids'*author">
<option values""> aBTop</option>
<?php foreach ($authors as $author): ?>
<option values"<?php htmlout($author['id']); ?>"><?php
htmlout($author['name']); ?></option>
<?php endforeach; ?>
</select>
</div>
<div>
<label for="category"> :</label>
<select namescategory" ids"category"
<option values""> /option
<?php foreach ($categories as $category); ?
<option values"<?php htmlout($category['id ]); ?"<?php
htmlout($category['name']); ?</option
<?php endforeach; ?
</select
</div>
<div>
<label for="text"> :</label>
cinput type="text" name="text" id="text">
</div>
<div>
<input type="hidden" name="action" value="search">
<input type="submit" value=""
</div>
</form>
< p x a href=" . ."> <//>
</body>
</html>

f o r e a c h , o p t i o n
s e l e c t . v a l u e o p t io n
a u t h o r c a t e g o r y ,
.
o p t i o n v a lu e ,
.
, m e th o d g e t . ,
,
URL
.
.

177

. 7.5.
'
) localhost/adrofo/jokes/

* |

00'

llM iillll



, :
:

:
: i

. 7.5.

,
. ,
SELECT,
. ,
, , .
, , SELECT , (chapter7 /admin/
jokes /index.php, ).
if (isset($_GET['action']) and $_GET['action'] == 'search')

{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
// SELECT.
$select = 'SELECT id, joketext';
$from
= ' FROM joke';
$where = ' WHERE TRUE';

WHERE .
, SELECT ,
. FROM
WHERE. (
), WHERE .
,

178

, ,
. WHERE TRUE, TRUE
1.
(
, , ), ,
SQL-. .
option value ",
$_GET [ ' author 1 ]
, , (chapter7/admin/
jokes/index.php, ).
$placeholders = array();
if ($_GET['author1] != '') //

{
$where .= " AND authorid = :authorid";
$placeholders[':authorid'] = $_GET['author'];

}

( . =). WHERE
, authorid joke
: authorid.
bindValue $_GET [ ' author 1] :
,
. :
$select, $f rom $where. ,
,
$placeholders, .
(chapter7/admin/jokes/
index.php, ).
if ($_GET['category'] 1= '') // .

{
$from .= ' INNER JOIN jokecategory ON id = jokeid';
$where .= 11 AND categoryid = :categoryid";
$placeholders[1:categoryid'] = $_GET['category'];

}
, ,
jokecategory, .
$f INNER JOIN
jokecategory ON id = jokeid. joke jokecategory
, id j id .
,
( ).
$where, ,
categoryid jokecategory
1 MySQL ,
WHERE 1.

179

(: c a t e g o r y i d ) . , , $ p l a c e h o l d e r s .
LIKE, 2,
( c h a p t e r 7 / a d m i n / j o k e s / i n d e x , php,
).
if ($_GET['text'] != '') // -

{
$where .= " AND joketext LIKE :joketext";
$placeholders[1:joketext'] = '%' . $_GET['text'] .

}
,
$_GET [ ' t e x t 1 ] (%). ,
LIKE ,
$_GET [ ' t e x t ' ] j o k e t e x t ,
.
SQL-, ,
( c h a p t e r 7 / a d m i n / j o k e s / i n d e x . p h p , ).
try

{
$sql = $select . $from . $where;
$s = $pdo->prepare($sql);
$s->execute($placeholders);

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p 1;
exit () ;

}
foreach ($s as $row)

{
$jokes[] = array('id' => $row['id']/ 'text' => $row['joketext']);

}
include 'jokes.html.php';
exit () ;

}
, .
$ p l a c e h o l d e r s ,
e x e c u t e , b in d V a lu e
.

. ,
HTM L- ( c h a p t e r 7 / a d m i n / j o k e s / j o k e s .h tm l .p h p ).
<?php include__once $_SERVER ['DOCUMENT_ROOT'] .
'/includes/helpers.inc.php'; ?>

180


<!DOCTYPE html>
<html lang="en">
<head>
cmeta c h a r s e t = " u t f - 8 ">

<title>ynpaBneHne : noncKa</title>
</head>
<body>

<111> noncKa</hl>
(isset($j o k e s ) ): ?>
<table>

<?php if

< t r x t h > T e K C T iiryTKH</th><th>flepicTBHH</th></tr>

<?php f o r e a c h ( $ jo k e s a s $ j o k e ) : ?>
<tr>

<tdx?php htmlout ($joke ['text']); ?></td>


<td>
<form action="?" method="post">
<div>
<input type="hidden" name="id" value="<?php
htmlout($joke['id'])? ?>">
<input type="submit" name="action" value="">
<input type="submit" name="action" value="">
</div>
</form>
</td>
</tr>

<?php e n d f o r e a c h ; ?>
</table>
<?php endif; ?>
< p x a href="?"> <//>
< p x a href =". ."> <//>
</body>
</html>

, . 7.6.

?
!

1
. 7.6.

181

,
,
.
.



( c h a p t e r 7 / a d m i n / j o k e s / s e a r c h f o r m . h t m l .php, ).
< p x a href =" ?("> <//>

. ,
a u t h o r c a t e g o r y , ,
, .
,
. .
, ,
$ t e x t (c h a p t e r 7 /a d m i n / j o k e s / f o r m , h tm l .p h p ,
).
<div>
clabel for="text"> :</label>
<textarea id="text" name="text" rows="3" cols="40"x?php
htmlout ($text) ; ?x/textarea>
</div>

,
( c h a p t 7 / a d m in / j o k e s / f o r m , h tm l .p h p , ).
<div>
<label for= *author>:</label>
<select name="author" id="author">
<option value="">Bbi6paTb</option>
<?php foreach ($authors as $author): ?>
<option value="<?php htmlout($author['id']); ?>"<?php
if ($author['id '] == $authorid)

{
echo ' selected';

}
? > x?php htmlout ($author [1name'] ) ; ?x/option>
<?php endforeach; ?>
</select>
</div>


,
. , ,
o p t i o n s e l e c t e d ,
( $ a u t h o r [ ' i d ' ] ) $ a u t h o r i d .

182

,
. ,
.
( c i n p u t ty p e = " c h e c k b o x " >) .
, :
name?
. ,
.
name, . 3
, ,
.
name .
: c a t e g o r i e s [ ].

____________________________

s e l e c t

,
option, .

m u l t i p l e = " m ultiple" .


option. : ,
, Ctrl
( Mac OS X).

, , ,
.
.
, ,
.
, .
, s e l e c t e d .
TRUE
$ c a t e g o r y [ ' s e l e c t e d ' ] ( c h a p t e r 7 / a d m i n / j o k e s / f o r m . h t m l . p h p ,
).
<fieldset>
<11>: </legend>
<?php foreach ($categories as $category): ?>
<divxlabel for= "category<?php htmlout ($category [1id ']) ;
?>"><input type="checkbox" name="categories[]"
id="category<?php htmlout($category['id ']); ?>"
value="<?php htmlout($category['id']); ?>"<?php
if ($category['selected'])

{
echo ' checked';

>
? <?php htmlout ($category ['name']) ; ?></labelx/div>
<?php endforeach; ?>
</fieldset>

183

,
. ( c h a p t e r 7 / a d m i n / j o k e s / f o r m ,
h t m l . php).
<?php include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/helpers.inc.php'; ?>
< IDOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<titlex?php htmlout ($pageTitle) ; ?></title>
<style type="text/css>
textarea {
display: block;
width: 100%;

}
</style>
</head>
<body>
< hl x ? php htmlout ($pageTitle) ; ?x/h l >
<form action="?<?php htmlout($action); ?>" method="post">
<div>
<label for="text"> :</label>
<textarea id="text" name="text" rows="3" cols="40"x?php
htmlout ($text) ; ?x/textarea>
</div>
<div>
<label for="author">:</label>
<select name="author" id="author">
<option value="">Bbi6paTb</option>
<?php foreach ($authors as $author): ?>
<option value="<?php htmlout($author['id']); ?>"<?php
if ($author['id'] == $authorid)

{
echo ' selected';

>
?<?php htmlout ($author ['name' ] ) ; ?x/option>
<?php endforeach; ?>
</select>
</div>
<fieldset>
<legend>KaTeropnn:</legend>
<?php foreach ($categories as $category): ?>
<divxlabel for="category<?php htmlout($category['id']);
?>"xinput type= "checkbox" name= "categories [] "
id="category<?php htmlout($category['id']); ?>"
value="<?php htmlout($category['id']); ?>"<?php
if ($category['selected'])

{
echo ' checked';

}
? <?php htmlout ($category['name']) ; ? x / l a b e l x / d i v >
<?php endforeach; ?>
</fieldset>
<div>
<input type="hidden" name="id" value="<?php
htmlout($id); ?>">

184


<input type="submit" value="<?php htmlout($button); ?>">
</div>
</form>
</body>
</html>

. 7.7.


:
, -
?

(
( 0

. 7.7.

,
.
,
.
. , .
,
, ( c h a p t e r 7 / a d m i n / j o k e s / i n d e x . p h p ,
).
<?php
include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/magicquotes.inc.php';
if (isset($_GET['add']))

{
$pageTitle = ' 1;
$action = 'addform';
$text = 1';
$authorid = '';
$id = " ;
$button = ' ';

185

7
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
// ,
try

{
$result = $pdo->query(1SELECT id, name FROM author');

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();

}
foreach ($result as $row)

{
$authors[] = array('id' => $row['id'],

'name' => $row['name']);

}
// ,
try

{
$result = $pdo->query('SELECT id, name FROM category');

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();

}
foreach ($result as $row)

{
$categories[] = array(
'id' => $row['id'],
'name' => $row['name'],
selected' => FALSE);

}
include 'form.html.php';
exit();

}
, ' selected'
$categor ies FALSE.
.

,
. ,
(chapter7 /admin/ jokes/index.php, ).
if (isset($_POST['action']) and $_POST['action'] == '')

{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.p h p ';
try

186

{
$sql = 'SELECT id, joketext, authorid FROM joke WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();

}
$row = $s->fetch();
$pageTitle = ' ';
$action = 'editform';
$text = $row['joketext1];
$authorid = $row['authorid'];
$id = $row['id'];
$button = ' ';
// ,
try

{
$result = $pdo->query('SELECT id, name FROM author');

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();

foreach ($result as $row)

{
$authors[] = array('id' => $row['id'],

'name' => $row['name']);

}
// , ,
try

{
$sql = 'SELECT categoryid FROM jokecategory WHERE jokeid = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $id);
$s->execute();

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();

foreach ($s as $row)

{
$selectedCategories[] = $row['categoryid'];

187

}
// ,
try

{
$result = $pdo->query('SELECT id, name FROM category');

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();

}
foreach ($result as $row)

{
$categories[] = array(
'id' => $row['id'],
'name' => $row['name'],
selected' => in_array($row['id'J, $selectedCategories));

}
include 'form.html.php';
exit();

}
(id, , ),
, .
.
1. SELECT jokecategory.
, ,
.
2. foreach
$selectedCategories.
3. ,
, ,
,
$selectedCategories.
in_array. (TRUE FALSE)
' selected',
.
.

. ,
.
( )
,
. : j.
, ,
$_POST [ 'author'].

188

, "",
(chapter7 /admin/jokes /index, php, ).
if (isset($_GET['addform']))

{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
if ($_POST['author] == ')

{
$error = ' .
.';
include 'error.html.p h p ';
exit();

}
try

{
$sql = 'INSERT INTO joke SET
joketext = :joketext,
jokedate = CURDATE(),
authorid = :authorid';
$s = $pdo->prepare($sql);
$s->bindValue(':joketext', $_POST['text']);
$s->bindValue(':authorid', $_POST['author']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.php';
exit();

}
$jokeid = $pdo->lastInsertId();


last Insert Id. , MySQL
(AUTO_INCREMENT).
, ,
.
, ,
jokecategory .
. , P H P -
. ,
.
, ,
. value
' o n '.
.
.
:
, , ,
.

189

:
, jokecategory .
, fo r e a c h
INSERT
.
if (isset($_POST['categories']))

{
try

{
$sql = 'INSERT INTO jokecategory SET
jokeid = :jokeid,
categoryid = :categoryid';
$s = $pdo->prepare($sql);
foreach ($_POST['categories'] as $categoryid)

{
$s->bindValue(':jokeid', $jokeid);
$s->bindValue(':categoryid', $categoryid);
$s->execute();

}
}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();
*

}
}
header('Locat ion: .1);
exit();

}
$ jo k e id ,
l a s t l n s e r t l d .
, , -
. :
1) j INSERT
UPDATE;
2)
j o k e c a te g o r y .
(c h a p t 7 / a d m in / j okes / in d e x . php, ).
, .
if (isset($_GET['editform1]))

{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php;
if ($_POST['author'] == '')

{
$error = ' .
.';

190


include 'error.html.php';
exit();

}
try

{
$sql = 'UPDATE joke SET
joketext = :joketext,
authorid = :authorid
WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST[1id']);
$s->bindValue(':joketext', $_POST['text']);
$s->bindValue(':authorid1, $_POST['author']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.php';
exit();

try

{
$sql = 'DELETE FROM jokecategory WHERE jokeid = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);

$s->execute();

}
catch (PDOException $e)

{
$error = '
.';
include 'error.html.php';
exit();

if (isset($_POST['categories']))

{
try

{
$sql = 'INSERT INTO jokecategory SET
jokeid = :jokeid,
categoryid = :categoryid';
$s = $pdo->prepare($sql);
foreach ($_POST['categories'] as $categoryid)

{
$s->bindValue(':jokeid', $_POST['id']);
$s->bindValue(':categoryid', $categoryid);
$s->execute();

}
}
catch (PDOException $e)

{
$error = ' .';

191

7
include 'error.html.p h p ';
exit();

}
}
header('Location: .');
exit();


, ,
. , ,
, .
: , j ,
jokecategory.
(chapter7 /admin/ jokes /index.
php, ).
if (isset($_POST['action']) and $_POST['action'] == '')

{
include $_SERVER[DOCUMENT_ROOT'] . '/includes/db.inc.php';
// ,
try

{
$sql = 'DELETE FROM jokecategory WHERE jokeid = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST[id']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();

}
// ,
try

{
$sql = 'DELETE FROM joke WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();

}
header('Location: .');
exit();

192



. , ,
, ,
. ,
.
, 11.
____________________________

, ,
( j) .
.
,
, .
:
,
.

,
,
, SQL. ,
, CMS
,
. , ,
.
,
. ,
, H TM L-,
,
h t m lo u t.
. -,
,
,
, h t m l s p e c i a l c h a r s . -,
,
,
, HTML.
,
, .
8 ,
, H TM L-.

.

, . ,
.
- .
,
.
, -
H TM L-
. HTML ,
. ,
H TM L- P H P -. ,
, , , ,
.
HTML.
, ,
.
. , ,
:
, . .
, ,
, .
h t m l o u t , ,
( c h a p t e r 7 / j o k e s / j o k e s . h t m l . php, ).
<?php htmlout($joke['text']); ?>


H TM L- , .
<?php echo $joke['text']; ?>

,
H TM L-, .
?
H TM L-,
.
, ,

194

, , ,
. ,

.
,
. ,
,
.
,
. HTM L .


, P H P -
HTML.
.
,
, , .
.
, ,
, -,
.
,
: .
, ,
, -, , .
, , ,
,
.
/A [\w\.\-]+@([\w\-]+\.)+[a-z]+$/i

, ? , ,
.
, , ,
, , .
. , , (
):
/ /

: .
, ( / ) ,
(#).
, , ( \ ).
.

195

,
, ( \ / ) ,
.
: ,
( \ # ).

,
.
p re g _ m a tc h . ,
.
( c h a p t 8 / p r e g _ m a t c h i / i n d e x . php).
<?php
$text

'PHP I'

if (preg_match('//', $text))

{
$output - 1$text & l d q u o ; P H P & r d q u o ; ;

}
else

{
$output = '$text &ldquo;PHP&rdquo;.

}
include 'output.html.p h p ';

, $ t e x t , ,
. , . 8.1
( ,
$ t e x t ).
- Mozilla Firefox
,

localhost/preg_matchl/

Stext .

. 8.1.

:
.
. ,
.
,
.

196

i . , / /
, , /P H P /i
, php .
( c h a p t e r 8 / p r e g _ m a t c h 2 / i n d e x .p h p ) .
<?php
$text = ' P h p ? 1;
if

(preg_match('/PHP/i1, $text))

{
$output = 1$text &ldquo;PHP&rdquo;.';

}
else

{
$output = '$text &ldquo;PHP&rdquo;.';

}
include

'o u t p u t .h t m l .p h p ';

. 8.2, ,
, .
- Mozilla Firefox
_

U-.IJ8L
!

localhost/preg_match2/

Stext '

. 8.2.

.
,
.
, preg_match.
, , .
/.*/

( 74), (. ) ( *) - ,
. ,
, ,
, .
, / .* /
PH, , , : ,
PH.

197


, .
(http://php.net/
manual/en/reference.pcre.pattern.syntax.php). .

.
,
.
( )

, ,
.

$ ( )

//
//
/$/
/$/

' I ' ' ? '.


' ' . ' , ' ?' .
' ', ' ? '.
'' .

. () , ,
( \ ) \
/ ...$/

( ).

* () ,
.
. ,
, / . * /
, . ,
, .
+ () , .
,
, .
? ( ) .
, ,

. , .
/?/
/+/
/*/

' ' ' ', ' '.


' ' ' ', ' '.
' ', ' ' ' ',

' ' .

/ [a-zA-Z]+$/ ,

( ) .

| ( )
, .
( ...) ( ) ,
, *, + ? (
).
, .
1 S,
.

198


/ (|)$/ ' ' ' ' .
/()+/
' ' ' ' , ' '
' '.
/( I )+ / ' ' ' ' , ' ' .

[...] ( ) ,
, .
, [ a q z ] ,
(a I q I z ), , [ a - z ],
(a Ib I I... I z ). ,
:
. , [ ] , '.
' 1 '
( ' 3 ' ) , ' ' ' 7 6 ' .
/ [ * 12345]/
' 1 '
( ' 9 ' ) , ' 1 ' ' 5 4 ' .
/[1-5]/
/ [ 1 2 3 4 5 ] / .
/ [-]$/

/ [-]$/
,
.
/ [0-9a-zA-Z]/ ,

/[12345]/

( ' 1 ' )

'39'

( ' ' )

'39'

.

.


, ,
(\):
/1\+1=2/ , '1 + 1 = 2 ' .
/\$\$\$/ , ' $ $ $ ' .

, .
,
. .
\ .
\ .
\ t .
\ s , ,
. , [ \ n \ r \ t ].
\ S . , [ \ n \ r \ t ] .
\ d . , [ 0 -9 ].
\D , . , [ 0 -9 ].
\w (). , [ a - z A - Z 0 - 9 _ ] .
\W ( ). , [ Aa -z A Z 0 - 9 _ ] .
\b : .
\ , .

199

\ \ . ,
\, / \ \ / , / \ / (
). \\ ,
/ \ \ \ \ / .

\ \ \ \ \ \ ____________________________________________
preg_match,
. ,
,
( \ \ ) .
/ \ \/ / \ \ \ \/ '.
, , .

,
, .
//4[\w\.\-]+@( [\w\-]+\. )+ [a-z]+$/i

/ , .
,
.
[ \w \ . \ ] + ,
( ) (), .
@ .
( [ \ w \ - ] + \ . ) + ( ) (
sitepoint., ),
() ( \ . ) .
[ a - z ] + , ,
( ) .
$ , .

/\ , .
i , [ a - z ]
.
, .
, - .
? :
,
.




, HTML. , ,
(, ** ...),
H TM L- ( < > </> ...).

200

preg_match
, .
,
H TM L-.
preg_replace.
preg_match,
, .
.
.
$newString = preg_replace(r e g E x p ,

rep la c e W lth ,

o ld S trin g ) ;

regExp , a replaceWith ,
, oldString.
,
$newString.
, .


6 htmlout
HTML.
helpers.inc.php.
HTML, (chapter8 /
includes/helpers .inc .php, ).
function markdown2html($text)

{
$text = html($text);
: HTML.
return $text;

}
, ,
Markdown, .

Markdown HTML,
-. ,
XHTML- HTML-
( Markdown, http://daringfireball.net/projects/markdown/).

markdown2html. htmlout,
HTM L-.
HTML, , 1.
1 B03M O ) K H O C T e f t M a r k d o w n ,
HTML. Markdown HTML-
, ,
Markdown.
, , cm/ieMarkdown.

201

, ,
.
, Markdown
(* ) (_). ,
/1. :
, .
.
/_ rj+ y
:
/ .
_ , ,
.
[_] ,
.
_ , .
/ .
,
preg_replace.
$ te x t = p r e g _ r e p la c e ( ' / _ [ _ ] + _ /',

' <></>', $ t e x t ) ;

.
, .
,
/. ,
.
preg_replace.
,

. $,
(1 , 2 , 99
). .
$ te x t = '';
$ te x t = p r e g _ r e p l a c e ( ' / ( . * ) ()/ ' ,
echo $ t e x t ; / / ''

' $ 2$1' , $ t e x t ) ;

$1 ,
, ( (. *)
, ).
. $2 ,
1, b i,
. H TM L
- s tr o n g .
, b i.

202

. , ' $2 $ 1 ' .
, ,
, .
/ _ ( [_]+)_/
.
, -
( c h a p t e r 8 / i n c l u d e s / h e l p e r s . i n c .p h p , ).
$text

= p r e g _ r e p l a c e ('/ _ ( [A_ ] + ) _ / ',

'< e m > $ l < / e m > ',

$text);


. , ,
,
( c h a p t e r 8 / i n c l u d e s / h e l p e r s . i n c .p h p , ).
$t e x t

= p r e g _ r e p l a c e ('/ \ * ( [ \ * ] + ) \ * / ',

'< e m > $ l < / e m > ', $ t e x t ) ;

, Markdown
( s t r o n g ) .
(* ^ * *
__ ).
.
/ __(.+ ?)__ /

, ?

[ *_] +. ,
. ,
.
:
(, ___ ). ,
.
, . + (
), 1.
/ _ ( . +) _ /

, + . -
, .
.

!__

1 S ,
, .

203


: .
, ,
. + .
, + ,
.
, . + ?
.
,
.
:
/__(. + ?)__ /s


. ,
( c h a p t e r 8 / i n c l u d e s / h e l p e r s . i n c .p h p ,
).
$text = preg_replace('/__(.+?)__ / s ' , '<strong>$l</strong>', $text);
$text = preg_replace('/\*\*(.+ ?)\*\*/s', '<strong>$l</strong>', $text);

,
s tr o n g ,
. , m arkdow n2htm l
, ( c h a p t e r 8 / i n c l u d e s / h e l p e r s .
i n c . php, ).
function markdown2html($text)

{
$text = html($text);
//
$text = preg_replace('/__(.+?)__ / s ' , ' <strong>$l</strong>', $text);
$text = preg_replace('/\*\*(.+ ?)\*\*/s', '<strong>$l</strong>, $text);
//
$text = preg_replace ('/_(.[ A_]+)_/', '<em>$l</em>', $text);
$text = preg_replace(' * ([A\*]+)\*/', '<em>$l</em>', $text);
return $text;

,
,
. ,
Enter.
(< b r >), (< / > ).

204

,
\, -,
\ , \ t .
Enter, . ,
Windows
( \ \ ) . Mac OS
( \ ), , Linux,
1.
, ,
:
// Windows (\r\n) Unix (\n).
$text = preg_replace('/\\/', "\n", $text);
// Macintosh (\r) Unix (\n).
$text = preg_replace('/\/', "\n", $text);

gga


, ,
, .
,
, .

. ," \ " ,
, / \/ ,
.
( /\/ ') , \
,
(" / \ \/" ) .
/ \/,
, .
, ,
.
- (" \ " ),
preg_replace.
,
.

,
( ) (
):
//
$text = '<>' . preg_replace('/\\/', '</><>', $text)
//
$text = preg_replace('/\/', ,<br>'/ $text);

. 1< />1;

1
, . ,
,
.
.

205

I
8

/ .
, ,
.
, :
,
. ,
.
,
, s t r _ r e p l a c e .
p r e g _ r e p l a c e ,
.
$newString = str_replace(s e a r c h F o r ,

re p la c e W ith ,

o l d S t r i n g );

, ( c h a p t e r 8 /
i n c l u d e s / h e l p e r s . i n c .p h p , ).
// Windows (\r\n) Unix (\n).
$text = str_replace(\r\n", "\n", $text);
// Macintosh (\r) Unix (\n).
$text = str_replace("\r", "\n", $text);
//
$text = '<p>' . str_replace(\n\n", '</p><p>'# $text)
//
$text = str_replace("\n", 1<br>1, $text);

. '< /p> ';

s t r _ _ r e p l a c e ,
, . ,
, s t r _ i r e p l a c e (
) p r e g _ r e p l a c e .

, ,
, .
M arkdown1.
[ ](URL )

: ,
URL.
,
HTML. ,
-
.
1 Markdown ,
. Markdown
.

206

,
. .
/ \ [ ( [\ ] ] + ) ] \ ( ( [
a zO9 . ~ : \ / ?#@! $&' ()*+,?=%]+)\ ) / i

.
, . ,
: ( () ),
($ 1) URL ($ 2 ).
, .
/ , .
\ [ .
,
.
( [ \ ] ] +) , ,
, - $ 1.
. ,
,
.
] \ ( ,

URL. ,
.
,
.
( [-a-z O -9
: \/?#@ ! $&' ()* + ,;= % ]+ ) ,
, , ,
-, $2.
URL1. ,
URL, + ,
.
( ) ) ,
. ( / ) .
, ,
\ /. ,
, , - z 0 - 9.
\ ) .
/ i , i ,
.
( c h a p t e r 8 /
i n c l u d e s / h e l p e r s . i n c .p h p , ).
1 ,
URL, .
, URL RFC 3986 (http://tools.
ietf.org/html/rfc3986#appendix-B).
.

207

8
$text = preg_replace(
' / \ [ ( [ \ ] ] + ) ] \ ( ( [ - a - z O - 9 . _ ~ : \ / ? # @ ! $ & \ 1 ( ) * + , ; = % ] + ) \ ) / i ' ,

'< href="$2">$l</a>', $text);

$1 $2
.
, , ,
.



M arkdown H TM L ( c h a p t e r 8 / i n c l u d e s /
h e l p e r s . i n c .p h p , ).
function markdown2html($text)

{
$text = html($text);
//
$text = preg_replace('/__(.+?)__ /s', '<strong>$l</strong>', $text);
$text = preg_replace('/\*\*(.+ ?)\*\*/s', '<strong>$l</strong>', $text);
// '
$text = preg_replace('/_([A_]+ )_/1, '<em>$l</em>', $text);
$text = preg_replace ('/\*([\*]+)\*/', '<em>$l</em>', $text)?
// Windows (\r\n) Unix (\n).
$text = str_replace("\r\n", "\n", $text);
// Macintosh (\r) Unix (\n).
$text = str_replace("\r", "\n", $text);
//
$text = '<p>' . str_replace("\n\n, ,< / p x p > ' / $text)
//
$text = str_replace("\n", ,<br>'/ $text);

. '</p>';

// [ ]( URL)
$text = preg_replace(
, / \ [ ( [ /N\ ] ] + ) ] \ ( ( [ - a - z 0 - 9 . _ ~ : \ / ? # @ ! $ & \ ' ( ) * + , ; = % ] + ) \ ) / i ,

'<a href="$2">$l</a>', $text);


return $text;

P H P -,
m arkdow nout. m ar kdown2 h tm l ( c h a p t e r 8 /
i n c l u d e s / h e l p e r s . i n c .p h p , ).
function markdownout($text)

{
echo markdown2html($text);

}
.
( c h a p t e r 8 / a d m in /
j o k e s / j o k e s . h t m l . php).

208


<?php include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/helpers.inc.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>YnpaBneHne : noncKa</title>
</head>
<body>
<1> no n cK a< /h l>
<?php if (isset($jokes)): ?>
<table>
< t r x t h > T e K C T iiiyTKH</th><th>flepiCTBHH</th></tr>

<?php foreach ($jokes as $joke): ?>


<tr valign="top">
< tdx?php markdownout ($joke ['text']) ? ? x / t d >
<td>

<form action="?" method="post">


<div>
<input type="hidden" name="id" value="<?php
htmlout($joke['id']); ?>">
<input type="submit" name="action" value="">
cinput type="submit" name="action" value="">
</div>
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
< p x a href =" ?"> <//>
< p x a href =". ." > <//>
</body>
</html>

( c h a p t e r 8 / j o k e s /
j o k e s . h t m l . php).
<?php include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/helpers.inc.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Cm*coK myTOK</title>
</head>
<body>
<> , :</>
<?php foreach ($jokes as $joke): ?>
<blockquote>
<P>
< ?php markdownout($ joke['text']); ?>
( <a href= "mailto:<?php htmlout($joke['email']); ?>"x?php
htmlout($joke['name']); ?></a>)
</p>
</blockquote>
<?php endforeach; ?>
</body>
</html>

209

,
: , Markdown,
, .
MARKDOWN_____________
Markdown
,
. ,
, ,
Markdown,
. Google,
Markdown (http://michelf.com/projects/php-markdown/)
markdown.php. includes.
Markdown,
markdown2html.
function markdown2html($text)

{
$text = html($text);
include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/markdown.php';
return Markdown($text);

}
Markdown, ,
- , , , ,
. -
.


,
, ,
. ,
, HTML,
, ,
Markdown, .
,
? , 4, ,
INSERT,
. ,
, .
, Markdown,
.

, .
,
. , :
.

9
,

(cookies) ,
, .
. ,
, .
.

,
.


, ,
. ,
. -
-
,
.
,
, (). ,
,
. - ,
,
. -
.
.
, (. 9.1),
.
1. URL, -.
s e t c o o k i e , .
2. , P H P -,
H T T P - s e t - c o o k i e , (,
m y c o o k ie ) , .
3. H T T P -,
m y co o k ie.

211

4. H T T P- cookie,
(=).
5. cookie,
$_1 cookie.

|
v

<?php

setcookH'mycooWeV

):

mycookiz:

-
set-cookie: mycookie*

HTTP-
cookie: myeookie*

. 9.1.
, set cookie ,
.
,

setcookie ( [ , v a l u e [ ,
h t t p O n l y ]]]]]])

e x p i r y T i m e [, p a t h [ , d o m a i n [ , s e c u r e [ ,

________
( [...]) ,
.
.

header, 4, setcookie
H T T P-,
- . setcookie
.
,
(, ).

212

setcookie .
,
, ( ). value
.

, . ,
,
expiryTime 1 1970
, .
time. ,
, expiryTime
t ime () + 3600. ,
, , (time () - 3600 * 24 * 365).
.
// .
setcookie('mycookie', 'somevalue', time() + 3600 * 24 * 365);
// .
setcookie('mycookie', '', time() - 3600 * 24 * 365);

path
. , ' / admin/ ',
,
admin .
: ,
/admin, /adminf /.
, ,
-.
,
, .
domain :
. ,
.
(, www.example.com support.example.com).
, ,
domain ' . example . c o m '.
: ,
example.com (, fakeexample.com).
secure 1,
(SSL) ( URL
https://).
1, ht tpOnly, ,
JavaScript . ,
JavaScript ,
, .
JavaScript-,
.
.

213

, P H P -
, JavaScript .
, , name, , ,
, . ,
set cookie domain,
expiry Time. ,
' ' (value, path domain) 0
(expiryTime secure).
. ,
, .
, ,
, .
(chapter9 /cookiecounter/index.php).
<?php
if (!isset($_COOKIE['visits']))

{
$_COOKIE['visits'] = 0;

}
$visits = $_COOKIE['visits'] + 1;
setcookie('visits', $visits, time() + 3600 * 24 * 365);
include 'welcome.html.p h p ';

, $_1 [ 1visi t s ' ].


, visit s
. $_1 [ 'visits ' ] 0.
$_COOKIE [ ' visits '],
.
, $_COOKIE [ ' visits ' ]
1. $visit s
. setcookie visits

.
, welcome.html.php
(chapter9/cookiecounter/welcome.h tml.php).
<?php include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/helpers.inc.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
cmeta charset="utf-8">
<title>C4eT4HK cookies</title>
</head>
<body>
<P>

<?php
if ($visits > 1)

214

,
echo " : $visits.";

}
else

{
//
echo ' -! ,
!';

}
?>
</>
</body>
</html>

. 9.2 , ,
.
, . 9.3.
------------------------------------------------------------------- cookies - Mozilla Firefox

[.

---

localhost/cookiecounter/

-! ,
!

. 9.2. ,

cookies - Mozilla Firefox

_________
localhost/cookiecounter/

-------

TTT

................

. 9.3. ,

215

, ,
.
, ,
20 . 50 ,
. ,
,
- , .
,
, .



.
-, ,
. ,
, ,
.
.
( ) ,
-.
.
, ,
, .

, .

.
, ,
( ) .
-1,
( ), .

, , php.ini
. (
), 1, ,
-, ,
. php.ini
, [ S e s s i o n ] . 20 ,
session.
, , :
session.save_handler
session.save_path
session.use_cookies

= files
= "C:\WINDOWS\TEMP"
= 1

1 -,
, MySQL.

216

s e s s i o n . s a v e _ p a th ,
. ,
,
. Mac OS X Linux
. W indows C:\WINDOWS\TEMP
(, D:\PHP\SESSIONS). ,
-, .
, ,
.
, s e s s i o n _ s t a r t .
, ,
.
, ,
( s e t c o o k i e ) .
session_start();

,
, $_
SESSIO N .
p a s s w o rd .
$_SESSION['password'] = 'mypassword';

, u n s e t .
unset($_SESSION[1password']);

, ,
, s e s s i o n _ d e s t r o y
.
$_SESSION = array();
session_destroy () ;

,
,
(http://www.php.net/session).
, ,
.
:
1) ,
;
2) ,
.
, ,
, ,
. ,

217

,
PayPal (http://www.paypal.com/). ,
, , ,
.
,
-.
. .
, , ,
, ,
.
, , , ,
.
( c h a p t e r 9 / s h o p p i n g c a r t / i n d e x .
php, ).
<?php
include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/magicquotes.inc.php';
$items = array(
array('id' => '1', 'desc'
'price' => 24.95),
array('id' => 1
'2', 'desc'
)',
'price' => 1000),
array('id ' => 1
'3', 'desc'
'price' => 19.99) ,
array('id' => '
14', 'desc'
'price' => 39.95));

=> '- ',


=> ' (

=> ' Goldfish ( 2 CD)',


=> ' JavaScript (SitePoint)',


: , . ,
,
, .
,
, .
,
( c h a p t e r 9 / s h o p p i n g c a r t / i n d e x . php, ).
session_start();
if (!isset($_SESSI0N['cart']))

{
$_SESSION[1cart'] = array();

}
s e s s i o n _ s t a r t (
) (
) .
$__SESSION [ ' c a r t ' ]
,
.

218

,
( c h a p t 9 / s h o p p i n g c a r t / i n d e x . php, ).
include

'c a t a l o g . h t m l . p h p ' ;

( c h a p t e r 9 / s h o p p i n g c a r t /
c a t a l o g . h t m l . php).
<?php include_once $_SERVER['DOCUMENT_ROOT'] .
'/ i n c l u d e s / h e l p e r s .i n c . p h p ';

?>

<!DOCTYPE html>
<html

lang="en">

<head>

<meta charset="utf-8">
<title>KaTanor TOBapoB</title>
<style>
table {
border-collapse:

collapse;

}
td, t h {
border:

lp x s o l i d b la ck ;

}
</style>
</head>
<body>

<> <?php
c o u n t ($_SESSION[ 1 c a r t ']);

echo
<pxa

href="?cart">IlpocMOTpeTb

?>

.</p>

<//>

<table border="l">
<thead>
<tr>
<th>OnncaHne TOBapa</th>
<th>heHa</th>
</tr>

</thead>
<tbody>
<?php

foreach

($items as

$ i t e m ) : ?>

<tr>

<tdx?php htmlout ($item ['desc']) ; ?></td>


<td>
$<?php echo number_format($item['price']/ 2); ?>
</td>
<td>

<form action="" method="post ">


<div>
<input

type="hidden"

name="id"

h t m l o u t ( $ i t e m [ 'i d ' ]);

< i n pu t

value="<?php

?>">

t y p e = "s u b m i t " n a m e = " a c t i o n "

v a l u e = " ">

</div>

</form>
</td>
< /t r >
<?php endforeach;

?>

</tbody>
</table>

219

9
<> .</>
</body>
</html>

, .
1. count
, $_SESSION [' c art'].
2. , . ,
,
.
3. number_f ormat
.
(http://www.php.net/number_format).
4. , ,
.
, ,
. 9.4.

:>-

- Mozilla Firefox
) localhost/shoppingcart/

24.95

(
)

1,000.00

Goldfish ( 2 CD)

19.99

JavaScript (SitePoint)

39.95

. 9.4.

, ,
$_POST [ 'a c t i o n '], ''.
( c h a p t e r 9 / s h o p p i n g c a r t / i n d e x ,
php, ).
if (isset($_POST['action']) and $_POST['action'] == '')

{
// $_SESSION['cart'].
$_SESSION['cart'][] = $_POST['id '];
header('Location: .');
exit();

220

$_SESSION [ ' cart 1 ]


, , .
,
.
,
$_GET [' car t '].
(chapter9 /shoppingcart /index.php, ).
if (isset($_GET['cart']))

{
$cart = arrayO;
$total = 0;
foreach ($_SESSION['cart'] as $id)

{
foreach ($items as $product)

{
if ($product['id'] == $id)

{
$cart[] = $product;
$total += $product['price'];
break;

}
}
}
include 'cart.html.p h p ';
exit();

}
$cart $ items,
, .
foreach.
$_SESSION [ 'c a r t '].
id ( $product [ ' i d ' ] ), $items.
$cart.
.
, foreach ,
($product [ 'price' ] ) $ total. break
foreach, .
$cart , cart.html.php
(chapter9/shoppingcart/cart .html .php).
,
$cart, $ items. .
<?php include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/helpers.inc.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Kop3HHa</title>
<style>

221

9
table {
border-collapse: collapse;

}
td, th {
border: lpx solid black;

}
</style>
</head>
<body>
<hl>Bama </111>
<?php if (count($cart) > 0 ) :
<table>
<thead>
<tr>

?>

<th>OnncaHne TOBapa</th>
<th>U;eHa</th>

</tr>
</thead>
<tfoot>
<tr>

<td>MToro:</td>
<td>$<?php echo number_format($total, 2); ?></td>
</tr>
</tfoot>
<tbody>
<?php foreach ($cart as $item): ?>
<tr>
<tdx?php htmlout ($item['desc 1]) ; ?></td>
<td>
$<?php echo number_format($item['price'], 2); ?>
</td>
< /tr>
<?php endforeach; ?>
</tbody>
</table>
<?php else: ?>
<> !</p>
<?php endif; ?>
<form action="?" method="post">
<P>
<a href="?"> </>
<input type="submit" name="action" value=" ">
</p>

</form>
</body>
</html>


$_SESSION[ ' c a r t ' ] ( c h a p t e r 9 / s h o p p in g c a r t / i n d e x . php, ).
if (isset($_POST['action']) and $_POST['action'] == ' ')

{
// $_SESSION['cart'].
unset($_SESSION['cart']);
header('Location: ?cart');
exit();

222

. 9.5 , ,
.
---------------------- - Mozilla Firefox
_____

localhost/shoppingcart/?cart

......

ft

24.95
-
Goldfish ( 2 CD) 19.99
39.95
JavaScript (SitePoint)
84.89
:

. 9.5.
(. 9.6).
- Mozilla Firefox
- ________________

localhost/shoppingcart/?cart

'

.--.

. 9.6. ,

223

( c h a p t 9 /
s h o p p i n g c a r t / i n d e x . php).
<?php
include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/magicquotes.inc.php';
$items = array(
array('id' => '1', 'desc'
'price' =>24.95),
array('id' => '2', 'desc'
)',
'price' => 1000),
array('id' => '3', 'desc'
'price' =>19.99),
array('id' => '4', 'desc'
'price' =>39.95));

=> '- ',


=> ' (

=> ' Goldfish ( 2 C D ) ',


=> ' JavaScript (SitePoint)',

session_start();
if (!isset($_SESSION['cart']))

{
$_SESSI0N['cart'] = array();

}
if (isset($_POST['action']) and $_POST['action'] == '')

{
// $_SESSION['cart'].
$_SESSION['cart'][] = $_POST['id '];
header('Location: .');
exit();

}
if (isset($_POST['action']) and $_POST['action'] == ' ')

{
// $_SESSION['cart'].
unset($_SESSION['cart']);
header(Location: ?cart');
exit();

}
if (isset($_GET['cart']))

{
$cart = array();
$total = 0;
foreach ($_SESSION['cart'] as $id)

{
foreach ($items as $product)

{
if ($product['id'] == $id)

{
$cart[] = $product;
$total += $product['price'];
break;

}
}
}

224

,
include 'cart.html.php';
exit();

}
include 'catalog.html.p h p ';


, ,
,
- . ,
, ,
,
.
,
. :
1) - ,
;
2)
.
-, ,
, . :
,
, ,
,
.

,
, .
? .
: ,

, , ,
.


, ,
. ,
, a u t h o r (. 9.7).
,
.

, .

225

, ,
. , ,
, .

. 9.7. a u t h o r

.
,
. ALTER TABLE ADD UNIQUE1,
phpMyAdmin.
ALTER TABLE author ADD UNIQUE (email)

MySQL ,
,
.
.
ALTER TABLE author ADD COLUMN password CHAR(32)

, NOT NULL
,
. P H P -
.
: CHAR ( 3 2 ) .
.
.
, , ,


.

md5.
$scrambled = m d 5 ($password . 'ijdb');

1 ,
. ,
ijdb.sql, .

226

' i j d b ',
,
-.
, :
, .
_____________
,
. ,
(, ),

. ,
, ,
.
,
( ).

md5 32 , , ,
.
, 32 , ,
. ,
, .
VARCHAR CHAR (32 ) ,
32 .
. md5 32-
, .
M ySQL MD5, .
, (
).
UPDATE author SET password = MD5('ijdb')
WHERE id = 1

, ,
P H P - ( ' i j d b ' ).
, ,
. ,
,
.
, ,
. . , ,
, CMS.
.
CREATE TABLE role (
id VARCHAR(255) NOT NULL PRIMARY KEY,
description VARCHAR(255)
) DEFAULT CHARACTER SET Utf8 ENGINE=InnoDB

227


. .
INSERT INTO role (id, description) VALUES
('', ', '),
(' ', ',
'),
(' ', ',
')

, ,
.
CREATE TABLE authorrole (
authorid INT NOT NULL,
roleid VARCHAR(255) NOT NULL,
PRIMARY KEY (authorid, roleid)
) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB

, .
INSERT INTO authorrole (authorid, roleid) VALUES
(1, ' ')

.
P H P -, .


, ,
. ,
,
, .
, ,
, .
,
H TM L-, (. 9.8).
CMS - Mozilla Firefox

localhost/admin/

----------------

?= |

?]

---------

00^

. 9.8.

228

,
, , ,
. ,
.
1. /admin/jokes/index.php , , , .
-.
2. /admin/authors/index.php , ,
.
, .
3. /admin/categories/index.php , ,
. ,
.
, ,
,
.
, , ,
,
.
,
, ( c h a p t e r 9 / a d m i n / a u t h o r s / i n d e x ,
php, ).
<?php
include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/magicquotes.inc.php';
require_once $_SERVER['DOCUMENT_ROOT'] . 1/includes/access.inc.php1;
if (iuserlsLoggedln())

{
include
exit();

/login.html.php';

}
if (luserHasRole(' '))

{
$error = '
.';
include '../accessdenied.html.php';
exit();

}
: .

,
( c h a p t e r 9 / a d m i n / c a t e g o r i e s / i n d e x , php,
, c h a p t e r 9 / a d m i n / j o k e s / i n d e x , php, ).
<?php
include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/magicquotes.inc.php';

229

9
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/access.inc.php1;
if (luserlsLoggedln())

{
include '../login.html.php';
exit();

}
if (1userHasRole(' '))

{
$error = ' .';
include '../accessdenied.html.php';
exit () ;

}
: .
<?php
include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/magicquotes.inc.php';
require_once $_SERVER['DOCUMENT_ROOT'] . 1/includes/access.inc.php';
if (luserlsLoggedln())

{
include '../login.html.php';
exit();

}
if (1userHasRole(''))

{
$error = ' .';
include '../accessdenied.html.php';
exit();

}
: .

, ,
:
1) login.html.php;
2 ) accessdenied.html.php;
3) access.inc.php :
u s e r l s L o g g e d l n
,
;
u s e r H a s R o le .

, admin index.html.

230

. , ,
$ , ( c h a p t e r 9 / a d m i n / a c c e s s d e n i e d .
h t m l . php).
<?php include_once $_SERVER['DOCUMENT_ROOT1] .
'/includes/helpers.inc.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>flocTyn 3anpei4eH</title>

</head>
<body>
<1> </]11>
< p x ? p h p htmlout ($error) ; ?></p>
</body>
</html>

, , ( c h a p t e r 9 / a d m i n /
l o g i n . h t m l . php).
<?php include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/helpers.inc.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=''utf-8">
<title>Bxofl</title>
</head>
<body>
<hl>Bxofl</hl>
<>, , ,
.</>
<?php if (isset($loginError)): ?>
< p x ? p h p htmlout ($loginError) ; ?></p>
<?php endif; ?>
<form action="" method="post"> 0
<div>
<label for="email">Email: <input type="text" name="email"
id="email"></label>
</div>
<div>
clabel for="password">: <input type="password" )
name="password" id="password"></label>
</div>
<div>
<input type="hidden" name="action" value="login">
<input type="submit" value="">
</div>
</form>

< p x a href ="/admin/"> <//> 0


</body>
</html>

231

,
. .
1. ,
. ,
, $ l o g i n E r r o r
, , .
2. fo rm a c t i o n ,
, . ,
,
.
3. t y p e i n p u t p a s s w o rd .
, ,
.
4.
userlsLoggedln ,
. , name="action"
input .
,
Enter , ,
, . ,
t ion ,
.
5. ,
, ,
. ,
.
.
. userlsLoggedln
,
.
( c h a p t e r 9 / a d m i n / l o g o u t . i n c .h tm l .p h p ).
<form action="" method="post">
<div>
<input type="hidden" name="action" value="logout">
<input type="hidden" name=ngoto" value="/admin/">
<input type="submit" value="">
</div>
</form>

a c t i o n ,
. g o to ,
, .
,
i n c l u d e ( c h a p t e r 9 / a d m i n / a u t h o r s / a u t h o r s .
h t m l . p h p ,; c h a p t e r 9 / a d m i n / c a t e g o r i e s / c a t e g o r i e s .h tm l .p h p ,
; c h a p t e r 9 / a d m i n / j o k e s / j o k e s .h tm l .p h p , ; c h a p t e r 9 /
a d m in / j o k e s / s e a r c h f o rm . h t m l . php, ).

232

< href =" .."> <//>


<?php include
/logout.inc.html.php'; ?>
</body>
</html>

< p x a href=" . ."> <//>


<?php include
/logout.inc.html.php'; ?>
</body>
</html>

< p x a href =" . ."> <//>


<?php include '../logout.inc.html.php'; ?>
</body>
</html>

< p x a href=" . ."> <//>


<?php include 1../logout.inc.html.php'; ?>
</body>
</html>


access.inc.php,
. , ,
, .
.
.

userlsLoggedln. TRUE,
, FALSE .
.
,
( $_POST [ ' a c t i o n ' ]
' l o g i n ' ),
.
TRUE.
$ l o g i n E r r o r
FASLE.
,
( $_POST [ ' action ' ]
'logout'),
, $_POST [ 'goto1].

userHasRole . ,
, .
, TRUE, FALSE.

233


(chapter9/includes/access .inc .php, ).
<?php
function userlsLoggedln()

{
if (isset($_POST['action']) and $_POST['action'] == 'login')

{
userlsLoggedln ,
(chapter 9/ includes /access .inc .php, ).
if (!isset($_POST['email']) or $_POST['email'] == '' or
!isset($_POST['password']) or $_POST['password'] == '')

{
$GLOBALS['loginError'] = ', ';
return FALSE;

}
, , ,
, .
,
$ loginError
$GLOBALS ( 6) FALSE.
,
. ,
, (chapter9/includes/
access .inc .php, ).
$password = md5($_POST['password'] . 'ijdb');

,
. ,
(chapter9/includes/access .inc .php, ).
function databaseContainsAuthor($email, $password)

{
include 'db.inc.php';
try

{
$sql = 'SELECT COUNT(*) FROM author
WHERE email = remail AND password = :password';
$s = $pdo->prepare($sql);
$s->bindValue(':email', $email);
$s->bindValue(':password', $password);
$s->execute();

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();

234

}
$row = $s->fetch();
if ($row[0] > 0)

{
return TRUE;

}
else

{
return FALSE;

}
}
.
db.inc.php
i n c l u d e 1. SELECT,
.
a u th o r , .
, TRUE, FALSE.
userlsLoggedln
databaseContainsAuthor (chapter9/includes/
access .inc .php, ).
if (databaseContainsAuthor($_POST['email'], $password))

{
,
, ,
. , .
1. ( ,
$_SESSION [ 'loggedln'] = TRUE).
: , ,
isUserLoggedln
TRUE.
2.
,
. , , -
,
databaseContainsAuthor.
, isUserLoggedln TRUE.
,

. :

.
111 include_once , $pdo,
db.inc.php, databaseContainsAuthor.
- ,
db.inc.php.

235

.
, . ,
, , ,
. .
cnoco6a(chapter9/includes/access.inc.php, ).
session_start();
$_SESSION[loggedln'] = TRUE;
$_SESSION['email'] = $_POST['email'];
$_SESSION['password'] = $password;
return TRUE;

}
, ,
, , ,
FALSE (chapter9 /includes /access .
inc.php, ).
else

{
session_start();
unset($_SESSION['loggedln'] ) ;
unset($_SESSION['email']);
unset($_SESSION['password']);
$GLOBALS['loginError'] =
' .';
return FALSE;

}
}
.
. ,
(chapter9/includes/access .inc .php, ).
if (isset($_POST['action']) and $_POST['action'] =?= 'logout')

{
session_start();
unset($_SESSION['loggedln']);
unset($_SESSION['email']);
unset($_SESSION['password']);
header('Location: ' . $_POST['goto']) ;
exit();

}
, ,
, , ,
(chapter9/includes/access .inc .php, ).
session_start();
if (isset($_SESSION['loggedln']))

{
return databaseContainsAuthor($_SESSION['email'],
$_SESSION['password']);

>
}

236

userlsLoggedln .
userHasRole. ,
, , ,
, .
, .
SELECT C O U N T (*) FROM author
INNER JOIN authorrole ON author.id = authorid
INNER JOIN role ON roleid = role.id
WHERE email = :email AND role.id = :roleId

author authorrole,
id authorid .
role, id
roleid authorrole. ,
WHERE
.
P H P -,
(chapter9/includes/access .inc .php, ).
function userHasRole($role)

{
include

'db.inc.php';

try

{
$sql = "SELECT C O U N T (*) FROM author
INNER JOIN authorrole ON author.id = authorid
INNER JOIN role ON roleid = role.id
WHERE email = :email AND role.id = iroleld";
$s = $pdo->prepare($sql);
$s->bindValue(1:e m a i l ', $_SESSION['email']);
$s->bindValue(':roleid', $role);
$s->execute();

}
catch

(PDOException $e)

{
$error = ' , .';
include 'error.html.php';
e x i t ();

}
$row = $s->fetch();
if

($row[0] > 0)

{
return TRUE;

}
else

{
return FALSE;

}
}

237

.
, ,

. , ,
. .

.
- , ,
.
access.inc.php ( c h a p t e r 9 / i n c l u d e s / a c c e s s . i n c .p h p ).
<?php
function userlsLoggedln()

{
if (isset($_POST['action']) and $_POST['action'] == 'login')

{
if (!isset($_POST['email']) or $_POST['email'] == '' or
!isset($_POST['password']) or $_POST['password'] == '')

{
$GLOBALS['loginError'] = ', ';
return FALSE;

}
$password = md5($_POST['password'] . 'ijdb');
if (databaseContainsAuthor($_POST['email'], $password))

{
session_start();
$_SESSION['loggedln'] = TRUE;
$_SESSION['email'] = $_POST['email'];
$_SESSION['password'] = $password;
return TRUE;

}
else

{
session_start();
unset($_SESSION['loggedln']);
unset($_SESSION['email']);
unset($_SESSION['password']);
$GLOBALS['loginError'] =
' .';
return FALSE;

}
}
if (isset($_POST['action']) and $_POST['action'] == 'logout')

{
session_start();
unset($_SESSION['loggedln'] ) ;
unset ($_jSESSION[ 'email'] ) ;
unset($_SESSION['password']);
header('Location: ' . $_POST['goto']);
exit();

238

session_start();
if (isset ($_SESSION['loggedln']))

{
return databaseContainsAuthor($_SESSION [1ema i l '],
$_SESSION['password' ]);

}
function databaseContainsAuthor($email, $password)

{
include

'db.inc.php';

try

{
$sql = 'SELECT C O U N T (*) FROM author
WHERE email = :email AND password = :password';
$s = $pdo->prepare($sql);
$s->bindValue(':email', $email);
$s->bindValue(1:password', $password);
$s->execute();

}
catch

(PDOException $e)

{
$error = ' .';
include 'error.html.php';
e x i t ();

}
$row = $s->fetch();
if

($row[0]

> 0)

{
return TRUE;

}
else

{
return FALSE;

}
function userHasRole($role)

{
include

'db.inc.php';

try

{
$sql = "SELECT C O U N T (*) FROM author
INNER JOIN authorrole ON author.id = authorid
INNER JOIN role ON roleid = role.id
WHERE email = remail AND role.id = :roleid";
$s = $pdo->prepare($sql);
$s->bindValue('remail', $_SESSION['email']);
$s->bindValue('rroleid', $role);
$s->execute();

}
catch

(PDOException $e)

239

{
$error = ' , .';
include 'error.h t m l .p h p ';
.e x i t ();

}
$row = $s->fetch();
if ($row[0]

> 0)

{
return TRUE;

}
else

{
return FALSE;


, ,
,
.
,
( c h a p t e r 9 / a d m i n /
a u t h o r s / f o r m . h t m l . php).
<?php include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/helpers.inc.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
cmeta charset="utf-8">
< t i t l e x ? p h p htmlout ($pageTitle) ; ?></title>
</head>
<body>
< h l x ? p h p htmlout ($pageTitle) ; ? x / h l >
<form action-"?<?php html o ut($action); ?>" method="post">
<div>
<label for="name"> : <input type="text" name="name"
id="name" value="<?php htmlout($name); ? > " x / l a b e l >
</div>
<div>
<label for= "email">Email: <input type="text" name="email"
id="email" value="<?php htmlout($email); ? > " x / l a b e l >
</div>

<div>
<label for="password"> : <input type="password"
name="password" id="password"></label>
</div>
<fieldset>
<legend>Roles:</legend>
<?php for ($i = 0; $i < count($roles); $i++): ?>
<div>
<label for="role<?php echo $i; ?>"><input type="checkbox"

240

,
name="roles[]" id="role<?php echo $i; ?>"
value="<?php htmlout($roles[$i]['id']); ?>"<?php
if ($roles[$i]['selected'])

{
echo ' checked';

>
?>><?php htmlout($roles[$i]['id']); ?></label>:
<?php htmlout($roles[$i]['description']); ?>
</div>
<?php endfor; ?>
</fieldset>
<div>
<input type="hidden" name="id" value="<?php
htmlout($id); ?>">
<input type="submit" value="<?php htmlout($button); ?>">
</div>
</form>
</body>
</html>

: ,
. ,
,
.
,
,
(. 7). .
,
i d i n p u t:
i d .
, .
,
f o r f o r e a c h ( c h a p t e r 9 / a d m i n / a u t h o r s / f o r m . h t m l .p h p ,
).
<?php for ($i = 0; $i < count($roles); $i++): ?>

$ i 0
. ,
$ r o l e s [ $ i ] , $ i i d
( c h a p t e r 9 / a d m i n / a u t h o r s / f o r m . h t m l .p h p , ).
id="role<?php echo $i; ?>"

, ( c h a p t e r 9 / a d m i n /
a u t h o r s / i n d e x . php). ,
,
(
).
<?php
include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/magicquotes.inc.php';

241

9
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/access.inc.php';
if (luserlsLoggedln())

{
include
e x i t ();

'../login.html.php';

}
if (luserHasRole(' '))

{
$error = '
.';
include '../accessdenied.html.php';
e x i t ();

if

(isset($_GET['add']))

{
include $_SERVER['DOCUMENT_ROOT'] . '/include s/d b .inc.p h p ';
$pageTitle = ' ';
$action = 'addform';
$name = '';
$email = 11 ;
$id = " ;
$button = ' ';

// ,
try

{
$result = $pdo->query('SELECT id, description FROM role');

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();

>
foreach ($result as $row)

{
$roles[] = array(
'id' => $row['id'],
'description' => $row['description'],
'selected' => FALSE);

}
include 'form.html.php';
exit () ;

>
if (isset($_GET['addform']))

{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
try

242

,
$sql = 'INSERT INTO author SET
,name = :n a m e ,
email = :email';
$s = $pdo->prepare($sql);
$s->bindValue(':name', $_POST['name']);
$s->bindValue(':e m a i l ', $_POST['ema i l ']);
$s->execute();

}
catch

(PDOException $e)

{
$error = ' .';
include 'e r ror.html.php';
e x i t ();

}
$authorid = $pdo->lastInsertId();
if ($_POST['password*] != '')

{
$password = md5($_POST['password'] . 'ijdb');
try

{
$sql = 'UPDATE author SET
password = :password
WHERE id = :id ';
$s = $pdo->prepare($sql);
$s->bindValue(':password', $password);
$s->bindValue(':id', $authorid);
$s->execute();

>
catch (PDOException $e)

{
$error = ' .';
include 'error.html.php';
exit();

}
}
if (isset($_POST['roles']))

{
foreach ($_POST['roles'] as $role)

{
try

{
$sql = 'INSERT INTO authorrole SET
authorid = :authorid,
roleid = :roleid';
$s a $pdo->prepare($sql);
$s->bindValue(':authorid', $authorid);
$s->bindValue(':roleid', $role);
$s->execute();

)
catch (PDOException $e)

{
$error = ' .';

243

9
include 'error.html.p h p ';
exit();

}
>
}
header('Location: .');
exit();

}
if (isset($_POST['action']) and $_POST['action'] == '')

{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
try

{
$sql = 'SELECT id, name, email FROM author WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();

}
$row = $s->fetch();
$pageTitle = ' ';
$action = 'editform';
$name = $row['name'];
$email = $row['email'];
$id = $row['id'];
$button = ' ';
// , ,
try

{
$sql = 'SELECT roleid FROM authorrole WHERE authorid = sid'?
$s = $pdo->prepare($sql);
$s->bindValue(':id', $id);
$s->execute();

>
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit()?

>
$selectedRoles = arrayO;
foreach ($s as $row)

{
$selectedRoles[] = $row['roleid'];

// ,
try

{
$result = $pdo->query( SELECT id, description FROM role );

>
catch (PDOException $e)

{
$error = ' .';
include 'error.html.php';
exit();

}
foreach ($result as $row)

{
$roles[] = array(
'id' => $row['id'],
'description' => $row['description'],
'selected' => in_array($row['id'], $selectedRoles));

include
e x i t ();

'form.html.php';

}
if

(i s s e t ($ _ G E T ['editform']))

{
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
try

{
$sql = 'UPDATE author SET
name = :n a m e ,
email = :email
WHERE id = :i d ';
$s = $pdo->prepare($sql);
$s->bindValue(':i d ' , $_POST['i d ']);
$s->bindValue(':name', $_POST['n a m e ']);
$s->bindValue(':em a i l ', $_POST['ema i l ']);
$s->execute();

}
catch

(PDOException $e)

{
$error = ' .';
include 'e r ror.h t m l .p h p ';
e x i t ();

if ($_POST['password'] != '')

{
$password = m d 5 ($_POST['password'] . 'ijdb');
try

{
$sql = 'UPDATE author SET
password = :password
WHERE id = :id';

245

9
$s = $pdo->prepare($sql);
$s->bindValue(':password', $password);
$s->bindValue(:id', $_POST['id']);
$s->execute();

>
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();

}
>
try

{
$sql = 'DELETE FROM authorrole WHERE authorid = :id'?
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();

>
if (isset($_POST['roles']))

{
foreach ($_POST['roles'] as $role)

{
try

{
$sql = 'INSERT INTO authorrole SET
authorid = :authorid,
roleid = :roleid';
$s = $pdo->prepare($sql);
$s->bindValue('sauthorid', $_POST['id']);
$s->bindValue(':roleid', $role);
$s->execute();

>
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();

}
>
}
header('Location:
exit();

}
if (isset{$_POST['action']) and $_POST['action'] == '')

{
include $_SERVER[1DOCUMENT_ROOT'] . '/includes/db.inc.php';

246

// , ,
try

{
$sql = 'DELETE FROM authorrole WHERE authorid = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id' , $_POST['id']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit();

// , ,
try

{
$sql = 'SELECT id FROM joke WHERE authorid = :id';
$s = $pdo->prepare($sql);
$s->bindValue(';id*, $_POST['id']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' , .';
include 'error.html.p h p ';
exit();

}
$result = $s->fetchAll();
// ,
try

{
$sql = 'DELETE FROM jokecategory WHERE jokeid = :id';
$s = $pdo->prepare($sql);
//
foreach ($result as $row)

{
$jokeid = $row['id'];
$s->bindValue(':id', $jokeid);
$s->execute();

}
}
catch (PDOException $e)

{
$error = ' .';
include 'error.html.p h p ';
exit () ;

// , ,
try

247

9
$sql = 'DELETE FROM joke WHERE authorid = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':i d ', $_POST['i d ']);
$s->execute();

}
catch

(PDOException $e)

{
$error = ' .';
include 'e r ror.h t m l .p h p ';
e x i t ();

}
// ,
try

{
$sql = 'DELETE FROM author WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':i d ' , $_POST['i d ']);
$s->execute();

}
catch

(PDOException $e)

{
$error = ' .';
include 'e r r o r .h t m l .p h p ';
e x i t ();

}
h e a d e r ('Location: .');
e x i t ();

}
// .
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
try

{
$result = $pdo->query('SELECT id, name FROM author');

}
catch

(PDOException $e)

{
$error = ' !';
include 'error.html.php';
e x i t ();

}
foreach ($result as $row)

{
$authors[]

= array('id'

=> $row['id'],

'name' => $ r o w ['n a m e ']);

}
include

'authors.h t m l .p h p ';

.
, . ,
. ,
.
, ,
.

248

:
, ,
.

.

,
. , .
,
, . 9.9.


, :
?
!
" * , - , ...", , , '
I
, ,
.

. 9.9.

, .
? (. 9.10).

'

- Mozilla Firefox

M l M i
localhost/addjoke/?addjoke

------------

*------------

:
, ,
.|

. 9.10.

249

,
, - (
). ,
. ,
, .
, ,
.
? ?
? ,
, , .
?
j o k e v i s i b l e ,
' YES ' () ' N 0 ' ()?
' N 0 ' ,
WHERE v i s i b l e = ' YES ' .
, ,
. (
, )
.
MySQL ,
, ENUM.
ALTER TABLE joke ADD COLUMN
visible ENUM('NO 1, 'YES') NOT NULL

(NOT NULL),
( ' N 0 ' ) ,
INSERT .
,
.
.
,
.
6,
. .

,
.
, ,
.
.
.
, , .
- , SitePoint,
(http://www.sitepoint.comorumsorumdisplay.php?34-PHP).

250


,
,
-.
. ,
, , .
, : ,
, .
, ,
.
-,
.
, .
CMS, .

, .
,
.
. , ,
. ,
.
,
. , ,
,
, .

.
,
1
, .
MySQL.
10
M ySQL-.
( ), ,
, .

10
MySQL

,
, .
MySQL.

. 1,
, M ySQL-
, , .
MySQL- ,
, , ,
, 1.
, ,
, ,
MySQL-, .
.
,
, .
,
.
.
, ,
,
. ,
MySQL-,
MySQL.
,
MySQL. ,
- ,
. , , M ySQL, .
, ,
, SELECT.
(, ) ,
( ) .
10 MySQL
, .
, , .

252

MySQL

, , ,
, MySQL .

MySQL
-, MySQL 24
.
. ,
, M ySQL-
, .
,
. MySQL
, ,
, .
, , ,
,
. ,
, ,
MySQL .
(, MySQL-
-) .
,
, MySQL
. ,
, MySQL

. , ,
.


phpMyAdmin
phpMyAdmin
MySQL, .
.
, (. 10.1).
[ i l 127.0.0.1

ijdb

SQL

( 4f
0 author
0

authorrole

category

| |

joke

@i

j|

i 1

}* ^ Q

*1

0 | | ^ |

4|

. 10.1.

253

10

SQL, ,
. 0,
. ijdb.sql,
i j d b .
, SQL-,
CREATE TABLE INSERT.
.
MySQL SQL.
.
, (
).
(, ,
).
.
, phpMyAdmin
. M ySQL-,
.
, ,
,
M ySQL-.


mysqldump
phpMyAdmin
, ,
. , phpMyAdmin .
- MySQL Linux, , , ,
,
. m ysqldum p.
m ysqldum p M ySQL- (
) ,
. SQL-,
. m ysqldum p
, , ,
phpMyAdmin.

?__________________________
,
. .
, ,
.
,
. , MySQL
, (
, ?)

254

MySQL

. MySQL-,
, - ,
, .

,
. ,
,
, .
, Windows -
, Kevs
Command Prompt Cheat Sheet ( ),
2002 (http://www.sitepoint.
com/command-prompt-cheat-sheet/).

M ySQL-,
, r o o t
p a s s w o r d i j db ijdb.sql1.
mysqldump -u root -ppassword ijdb > ijdb.sql

,
SQL- phpMyAdmin2
m y sq l.
mysql -u root -ppassword ijdb < ijdb.sql

M ySQL-, i j db
SQL,
.
, ,
.



, , MySQL,
.
phpMyAdmin
m ysqldum p.
, M ySQL-
, , SQL-,
1 mysqldump, MySQL,
bin , ( Mac OS X
/Applications/AMP/Ljbrary/bin, XAMPP mysql),
.
2 SQL-, phpMyAdmin,
mysqldump ,
. , ,
.

255

10

.
INSERT, UPDATE DELETE, SELECT.
,
, ,
. ,
phpMyAdmin mysqldump,
, , .
,
. ,
DROP TABLE,
, ( )
.
,
, , ,
DROP.
M ySQL- ,
(my.ini W indows my.cnf Mac OS X Linux).
,
. MySQL
.

.

MY.INI MY.CNF?

-----------------------------------------------------------------------------------------------------------------

Windows my.ini,
C:\xampp\mysql\bin\my.ini.
.
MySQL, ( Mac OS X),
/etc/my.cnf, .
, Finder
,
, /etc ,
.
sudo mv my.cnf /etc/

,
l o g - b i n [mysqld] .
, [mysqld]
.
l o g - b i n M ySQL-,
. , Windows
M ySQL1.
[mysqld]
log-bin="C:/xampp/mysql/data/binlog"

1 , MySQL Windows
(/), (\).

256

MySQL

Mac OS X .
[mysqld]
log-bin=/Applications//logs/binlog

M ySQL binlog.000001,
binlog.000002 . .
, .


,
MySQL. ,
.

, M ySQL-.
.
,
.

. , MySQL
. ,
m ysqldum p.
mysqldump -u root -ppassword --flush-logs --master-data=2 --deletemaster-logs ijdb > ijdb.sql

- - f l u s h - l o g s MySQL- ,
( ).
- - m a s t e r d a t a = 2 , m ysqldum p
ijdb.sql ,
,
. , - - d e l e t e - m a s t e r - l o g s
m ysqldum p , ,
, .

,
, .
M ySQL-
, .
m y s q lb in lo g .
m y s q l b i n l o g MySQL
SQL, . ,
,
. m y s q l b in l o g
SQL-,
M ySQL-, ,
m ysqldum p.
mysqlbinlog binlog.000041 binlog.000042 > binlog.sql
mysql -u root -ppassword < binlog.sql

257

10

MySQL
2 , mysql,
M ySQ L-, ,
. 4 , phpM y Admin
,
.
MySQL ,
(http://dev.mysql.eom/doc/refman/5.5/en/
privilege-system.html). ,
, mysql: u s e r , db, h o s t , t a b l e s _ p r i v
c o lu m n s _ p r i v .
INSERT, UPDATE DELETE,
MySQL.
MySQL-, phpMy Admin.
MySQL ,
,
.

,
phpMy Admin ,
MySQL-, ,
(, ,
mysql , ),
: ? ,
www.example.com. : www.example.com localhost?
, ,
. ,
( mysql PD O ),
. ,
- (
), .
, MySQL-
, ,
: , www.example.com,
localhost. ,
, .
, MySQL,
, ,
(, %.example.com), .
,
M ySQL- . ,
,
( , www.example.com ,
%.example.com , % ).

258

MySQL

1 MySQL
(
, , localhost,
) . ,

.
,
www.example.com M ySQL-,

j e s s . ,
.

localhost
www.example.com

root

root

jess

localhost
www.example.com
%.example.com

, j e s s ,
.
www.example.com, MySQL-
( ).
j e s s , , (
), M ySQL-
. j e s s ,
, ,
,
.
:
(DELETE FROM m y s q l .u s e r WHERE U s e r = " " ) ,
,
( localhost
).

root

www.example.com

root

localhost

jess

www.example.com

jess

jess


localhost

localhost
www.example.com
%.example.com

1 , , ,
.

259

10

(
) ,
, .

localhost

root

www.example.com

root

%.example.com

jess

?
MySQL- ,
, ,
. ,
, MySQL,
, M ySQL-,
. , ,
.

__________
,
MySQL,
. MySQL- ,
, ,
, r o o t.
. W indows,

Kev's C om m and Prompt C heat S h eet (
, http://www.sitepoint.com/command-prompt-cheat-sheet/).

M ySQL-.
m y sq la d m in ,
. .
Windows, : MySQL
M ySQL-. Mac OS X Linux
ps. P ID -,
M ySQL-,
.
k i l l p id

p i d MySQL-.
, .
k i l l -9 , :
. ,
,
.

260

MySQL

, , ,
s k i p - g r a n t - t a b l e s .
M ySQL- my.ini my.cnf (

).
[mysqld]

skip-grant-tables

M ySQL ,
.
,
.
( phpMyAdmin
m y sq l), .
UPDATE mysql.user SET Password=PASSWORD("newpassword")
WHERE User="root"

M ySQL- s k i p - g r a n t t a b l e s .


, M ySQL
, SELECT.
.
j
, . ,
- .
SELECT joketext FROM joke WHERE id = 1234

, M ySQL-
i d jo k e ,
1234. ,
M ySQL- ,
, ,
.

, -, ,
WHERE
.
. , id
j . , phpMyAdmin,
j ,
(. 10.2).

261

10
flriteBBW ...] 1 ' . ! & &
0 PRIMARY
BTREE

.
id
4

Null

. 10.2.

:
i d . (PRIMARY) ,
: , i d
j .
, i d .
CREATE TABLE joke

id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,


joketext TEXT,
jokedate DATE NOT NULL,
authorid INT
) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB;

KEY , a PRIMARY
, , ,
. . 10.2 ,
.
,
i d . , WHERE,
, .
, MySQL- ,
SELECT: EXPLAIN.
EXPLAIN SELECT joketext FROM joke WHERE id = 1

________________
,
1, .
, 1234, MySQL-
, j ,
.

EXPLAIN phpMyAdmin
, . 10.3.

id select type table type possible keys key


1 SIMPLE

joke

const PRIMARY

key ten ref

PRIMARY 4

const

rows Extra
1

. 10.3. SELECT PRIMARY

, SQ L, , i d (,
a u t h o r i d ) .

262

MySQL

SELECT,
.
SELECT * FROM joke WHERE authorid = 2

MySQL EXPLAIN (. 10.4).

id selectJype table type possible keys key


1 SIMPLE

joke

ALL

keyjen ref

NULL NULL

rows Extra

NULL NULL

4 Using where

. 10.4. NULL

, M ySQL-
.

, a u t h o r i d .
!____________
i d a u t h o r
, ,
a u t h o r . WHERE
j o k e a u t h o r i d , .

phpMyAdmin j .
1 /,
(. 10.5).

authorid
INDEX

authorid [ i n t ( l l ) ]

[ 1 () )

L.

;.~~~~*2,-----

. 10.5. a u t h o r i d

263

10

.
. (
).
. , PRIMARY
INDEX. , UNIQUE ()
FULLTEXT (). ,
,
.
. a u t h o r i d .
. ,
( , , ).
0, , PRIMARY .
MySQL SELECT,
EXPLAIN, ,
a u th o rid .
,
. ,
. ,
(, INSERT UPDATE),
MySQL- , ,
.
, , SELECT
, .
, i d ,
. , , j o k e c a t e g o r y .
CREATE TABLE jokecategory (
jokeid INT NOT NULL,
categoryid INT NOT NULL,

PRIMARY KEY (jokeid, categoryid)


) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB;

: j o k e i d c a t e g o r y i d .
. 10.6 , phpMyAdmin.

PRIMARY

.. *
BTREE

*
jokeid

categoryid 4

. 10.6.

.
,
. , , ,
id 3 id 4 ( ).
SELECT * FROM jokecategory WHERE jokeid = 3 AND categoryid = 4

264

MySQL


( j id). ,
, id 1,
.
SELECT name
FROM jokecategory
INNER JOIN category ON categoryid = category.id
WHERE jokeid = 1


, ,
,
i d . , , a u t h o r i d
j i d a u t h o r .
,
, . ,
a u t h o r i d , i d
author.

, MySQL .
, a u t h o r i d
a u t h o r . a u t h o r i d ,
a u th o r , MySQL-
: a u t h o r i d .
MySQL
,
. ,
CREATE TABLE
ALTER TABLE (chapt er 10 /sql /ijd b .sql, ).
CREATE TABLE joke (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
joketext TEXT,
jokedate DATE NOT NULL,
authorid INT,
FOREIGN KEY (authorid) REFERENCES author (id)
) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB
ALTER TABLE joke
ADD FOREIGN KEY (authorid) REFERENCES author (id)

phpMyAdmin
. , (
a u t h o r i d ) .
, MySQL , phpMyAdmin
. a u t h o r i d ,
j (. 10.7).

265

10
3 jokedate date

4 authorid

/ :
!)
|

^
() #

id

. 10.7.

j
,
. (INNODB) authorid
'ijdb' . 'author' . 'id' (ijdb ).
1,
RESTRICT ON DELETE ON UPDATE (. 10.8).
.

. 10.8. phpM y A dm in

, MySQL
j authorid ,
author. ,
author, j.
, , , ,
j phpMy Admin,
authorid author.
, MySQL , , phpMy Admin
.

, .
, ALTER TABLE,
(: , ).
1 phpM yAdm in
( ).
phpM yAdm in, M ySQL
.

266

MySQL
ALTER TABLE jokecategory
ADD FOREIGN KEY (jokeid) REFERENCES joke
ALTER TABLE jokecategory
ADD FOREIGN KEY (categoryid)

(id)

REFERENCES category

ALTER TABLE authorrole


ADD FOREIGN KEY (authorid) REFERENCES author
ALTER TABLE authorrole
ADD FOREIGN KEY (roleid) REFERENCES role

(id)

(id)

(id)

____________________
,
(, ,
), .
MySQL
. :
( )
, , n u l l (
a u t h o r i d ).
ON r e s t r i c t o n u p d a t e
phpMyAdmin.
MySQL- ,
, ,
. , phpMyAdmin
, PHP-, ,
, .
, - :
PHP- .
, .
PHP-
,
.

,
, .
, (
MySQL, , ,
,
),
, , , ,
M ySQL-,
.
11
SQL,
, .

11
SQL-

,
SQL ,
CREATE TABLE INSERT.


, .

SELECT.


SELECT
,
, .
,
, .
SELECT,
, . ,
a u t h o r .
SELECT id, , email FROM author

,
. 11.1.

thatguy@kevinyank.com

joan@example.com

3 molly@faerie.com
4

amym@example.cpro

. 11.1.
,
. , ,
, , ,
. .

268

SQL-
SELECT id, name, email FROM author ORDER BY name

. 11.2.

. 11.2. ,
WHERE, ,
SELECT ORDER BY. ,
.
DESC, ,
(. 11.3).
SELECT id, name, email FROM author ORDER BY name DESC

4 amym@exampf com
3 molly@feerie.com
1

thatguy@kevinyank.com

joan@example.com

. 11.3. ,
ORDER BY
,
. MySQL
,
. . , ORDER BY,
DESC,
.
, ,
, MySQL .
, ( ),
( , ,
10).


,
. , .
j t im e s v ie w e d

269

11

, ,
. ,
, .
, times viewed,
.
try

{
$sql = 'UPDATE joke SET
timesviewed = timesviewed + 1
WHERE id = :i d ';
$s = $pdo->prepare($sql);
$s->bindValue(':i d ' , $id);
$s->execute();

}
catch

(PDOException $e)

{
$error = '
. ';
include 'error.html.php';
e x i t ();

}

.
timesviewed (ORDER BY timesviewed DESC),
. ,


,
.
LIMIT,
. .
$sql = 'SELECT joke.id, joketext, name, email
FROM joke INNER JOIN author
ON authorid = author.id
ORDER BY timesviewed DESC

LIMIT 10';

,
DESC.
, ,
, 1.
, ,
, .
LIMIT: ,
, .
,
21- 25-.
1 - :
(ObjectOriented PHPiPagingResultSets; http://
www.sitepoint.com/php-paging-result-sets/).

270

SQL-
$sql = 'SELECT joke.id, joketext, name, email
FROM joke INNER JOIN author
ON authorid = author.id
ORDER BY timesviewed DESC

LIMIT 20# 5';

, ,
21- 20.


SQL- ,
. .
, :
, , ,
, .
, ,
, .
, , ,
, . ,
, ,
.
,
, .
, SQL- START TRANSACTION.
START TRANSACTION

SQL-
COMMIT.
COMMIT

, ,
,
ROLLBACK.
ROLLBACK

ROLLBACK .
, , ROLLBACK

.
P H P - PD O
: beginTransaction ,
commit , a rollBack .
try

{
$pdo->beginTransaction();

271

11

: ...

$pdo->commit();

}
catch

(PDOException $)

{
$pdo->rollBack();
$error = ' .';
include 'error.h t m l .p h p ';
e x i t ();

InnoDB
,
InnoDB (e n g i n e ^InnoDB), .
MylSAM .


M ySQL
.
, SitePoint
.
,
airline.sql .

f1ight ity. f1 ight
: ( origincityid),
( des t inat ionci ty id), , ,
( ). city
, . , or igincityid destinationcityid flight
, city.
(. 11.4),
.
SELECT flight.number, city.
FROM flight INNER JOIN city
ON flight.origincityid = city.id

(. 11.5)
.
SELECT flight.number, city.name
FROM flight INNER JOIN city
ON flight.destinationcityid = city.id

272

SQL-

110

number name

226

QF2026

QF2027

226

110

QF2027
. 11.4.

QF2Q26
. 11.5.

,
, .
SELECT flight.number, city.name, city.name
FROM flight INNER JOIN city
ON flight.origincityid = city.id
INNER JOIN city
ON flight.destinationcityid = city.id

, , phpMyAdmin :
#1066 Not unique table/alias: 'city'.
?
, . M ySQL flight, city city.
.
, .
, ( )
, id city origincityid
destinationcityid. , id city
origincityid destinationcityid .
, ,
. ,
, ,
.
city,
MySQL .
: ,
.
city ( origin, destination).
?
, city ( )
.
SELECT,
FROM, AS , ,
.
, , city
origin.

273

11
SELECT flight.number, origin.
FROM flight INNER JOIN city AS origin
ON flight.origincityid = origin.id

, , ,
.
f f l i g h t o r i g i n
, .
. ,
c i t y ,
( )
(. 11.6).
SELECT flight.number, origin., destination.name
FROM flight INNER JOIN city AS origin
ON flight.origincityid = origin.id
INNER JOIN city AS destination
ON flight.destinationcityid = destination.id

.
(. 11.7).
SELECT f.number, .name AS origin, d.name AS destination
FROM flight AS f INNER JOIN city AS
ON f .origincityid = o.id
INNER JOIN city AS d
ON f .destinationcityid =,d.id

number name

name

110

226

QF2026
QF2027 *

. 11.6.

number origin
110

destination

*
QF2026
QF2027

. 11.7.

,
.
a u t h o r : ,
. .


2, , j ,
.
SELECT COUNT(*) FROM joke

COUNT ,
, .

274

SQL-

MySQL ( ; http://dev.mysql.com/doc/mysql/en/group-by-functions.html)
. ,
, SELECT,
.
COUNT .
,
. , , ,
,
, id,
COUNT. P H P - (
).
// .
$result = $pdo->query('SELECT id, name FROM author1);
// ,
foreach ($result as $row)

{
$authors[] = array(
'id' => $row['id'],
'name' => $row['name']

);
}
// , .
$sql = 'SELECT COUNT(*) AS numjokes FROM joke WHERE authorid = :id';
$s = $pdo->prepare($sql);
// ,
foreach ($authors as $author)

{
$s->bindValue(':id 1, $author['id']);
$s->execute();
$row = $s->fetch();
$numjokes = $row['numjokes'];
// .
$output .= htmlspecialchars($author['name'], ENT_QUOTES, 'UTF-8')
. " ($numjokes jokes)<br>";

}
, AS,
COUNT ( * ) .
, + 1 ,
.
, ,
,
. SELECT.
SELECT GROUP BY, , MySQL
.
. ,
COUNT, ,

275

11

. ,
, .
SELECT author.name, COUNT(*) AS numjokes
FROM joke INNER JOIN author
ON authorid = author.id
GROUP BY authorid

, . 11.8, ,
SELECT.
num jokes

3
1

. 11.8.

,
GROUP BY author.id ( , , FROM
). GROUP BY author.name
. ( ),
, .
, ,
.


,
, .
,
. j ,
authorid ,
ON
.
,
, author
.
: ,
j - ,
(, authorid).
, , .
INNER JOIN ( ),
, MySQL .
, , , INNER JOIN.
MySQL
(. 11.9). ,
, : 1

276

SQL-

1 1 2; 1 1 2 2; 2
1 1 2 , , 2 1 2
2. , MySQL ON ,
, , id
authorid .
,
1 ( author),
2 (j ).
( ),
( ).
, , NULL.

. 11.9.

MySQL ,
LEFT JOIN INNER JOIN FROM.
, .
SELECT author.name, COUNT(*) AS numjokes
FROM author LEFT JOIN joke
ON authorid = author.id
GROUP BY author.id

.
1. author LEFT JOIN joke, joke LEFT JOIN
author. , ,
. LEFT JOIN
, ( author).
2. GROUP BY authored GROUP BY author, id.
author.id id author, a authored

277

11

j. SELECT
, . LEFT
JOIN ,
author, j, NULL
, j. authorid.
GROUP BY authorid,
, ,
LEFT JOIN authorid
NULL.
, , . 11.10.

1
1

. 11.10. - ...
, ,
. , .
COUNT ( *) , .
,
LEFT JOIN, , .
SELECT author.name, joke.id AS jokeid
FROM author LEFT JOIN joke
ON authorid = author.id

,
(. 11.11), , j,
LEFT JOIN. ,
NULL, COUNT (* )
.

. 11.11.

SQL-

* (,
j .id), COUNT NULL
, (. 11.2).
SELECT author.name, COUNT(joke.id) AS numjokes
FROM author LEFT JOIN joke
ON authorid = author.id
GROUP BY author.id

. 11.12 .


HAVING
,
? ,
.
SELECT author.name, COUNT(joke.id) AS numjokes
FROM author LEFT JOIN joke
ON authorid = author.id
WHERE numjokes = 0
GROUP BY author.id

, phpMyAdmin
#1054 - Unknown column 'numjokes' in 'where clause'.
, WHERE num jokes = 0 ,
, MySQL- .
,
author joke . ON,
FROM, ( ,
, , num jokes
0). MySQL GROUP BY:
authorid,
COUNT , NULL j.id,
numj okes.
, numj okes ,
GROUP BY, , , WHERE.
, - , WHERE
numj okes, .

279

11

, ,
WHERE,
GROUP BY. ,
,
HAVING.
(. 11.13).
SELECT author.name, COUNT(joke.id) AS numjokes
FROM author LEFT JOIN joke
ON authorid = author.id
GROUP BY author.id
HAVING numjokes = 0

numjokes

........................

. 11.13. ,

, HAVING,
WHERE. ,
, a u t h o r . != ' '
. ,
.
WHERE,
MySQL .


,
MySQL .
SELECT,
, . ,
MySQL-
.
,
. MySQL ,
,
(. ). MySQL,
,
. , TIMESTAMP
. MySQL
(http://dev.mysql.eom/doc/refman/5.5/en/datetime.html),
.
SQL,
( , ),
Simply SQL ( SQL; http://www.sitepoint.com/books/sql1/).

12

, ,
: , , ...
. ,
?
,
.
,
( ), -
. :
, ,
MySQL.
,
-.


() -, , ,
, . ,

, ,
.
H TM L-,
,
-,
.
, ,
. , , sitepoint.com,
.
: , ? ,
, ? ,
?
-, ,
, .
,
- ,
.

281

12

, index.php,
.
, , , ,
. ,
,
. ,
.
, P H P -, ,
index.html, .
,
, .
, , ,
.
file _

g e t _ c o n t e n t s . ,
. ,
, URL .
FALSE.

fi

l e _ p u t _ c o n t e n t s .
. 1. ,
, (
), .

file

_ e x i s t s . , .
, FALSE.

. .
u n l i n k . .
( c h a p t e r l 2 /
r e c e n tjo k e s /c o n tr o lle r .p h p c h a p te r12/r e c e n tjo k e s /jo k e s .h tm l.
php), ,
( 10).
<?php
include_once $_SERVER[1DOCUMENT_ROOT'] . '/includes/db.inc.php';
try

{
$sql = 'SELECT id, joketext FROM joke
ORDER BY jokedate DESC
LIMIT 3';
$result = $pdo->query($sql);

}
catch (PDOException $e)

{
$error = ' .';
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit ();

1
(http://php.netAile_put_contents).

282

}
foreach ($result as $row)

{
$jokes[]

= array('text'

=> $row['joketext']);

}
include

'jokes.html.php';

<?php include_once $_SERVER['DOCUMENT_ROOT'] .


'/includes/helpers.inc.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>IIocneflHne myTKH</title>

<link rel="canonical" href="/recentjokes/">


</head>
<body>
<> :</>
<?php foreach ($jokes as $joke): ?>
<?php markdownout($j o k e ['t e x t ']); ?>
<?php endforeach; ?>
</body>
</html>

index.php,
http://www.example.com/recentjokes/
. controller.php.
, , , l i n k
r e l = " c a n o n i c a l " 1 jokes.html.php, ,
http://www.example.com/recentjokes/. , URL,
.

generate.php. controller.php (

), ,
index.html.
index.html , - . ,
tempindex.html,
, , index.html.
,
: P H P -, ,
, ( c h a p t e r l 2 / r e c e n t j o k e s /
g e n e r a t e . php, ).
<?php
$srcurl = 'h t t p ://localhost/recentjokes/controller.php';
$t emp f i1ename = $_SERVER['DOCUMENT_ROOT'] .
'/recentjokes/tempindex.html';
$targetfilename = $_SERVER['DOCUMENT_ROOT'] .
'/recentjokes/index.html';

1 GoogleWebmasterCentralBlog (http://
googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.html).

283

12

SSRCURL URL_______________________
I V )

$srcurl controller.php
- , .
, controller.php
URL, - .
, controller.php,
.

,
.
f i l e _ e x i s t s , , , u n l i n k
( c h a p t e r 1 2 / r e c e n t j o k e s / g e n e r a t e .p h p , ).
if (file_exists($tempfilename))

{
unlink($tempfilename);

}
c o n t r o l l e r . p h p ,
f i l e _ g e t _ c o n t e n t s .
, a URL, , ,
- H TM L-
( c h a p t e r l 2 / r e c e n t j o k e s / g e n e r a t e . p h p , ).
$html = file_get_contents($srcurl);
if (!$html)

{
$error = "He $srcurl.
!";
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit();

}
, $ h tm l,
H T M L -, f i l e _ p u t _ c o n t e n t s
( c h a p t e r l 2 / r e c e n t j o k e s / g e n e r a t e .p h p , ).
if (lfile_put_contents($tempfilename, $html))

{
$error = "He $tempfilename.
!";
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit();

}
, . ,
,
u n l i n k ( c h a p t e r l 2 / r e c e n t j o k e s / g e n e r a t e .p h p , ).
copy($tempfilename, $targetfilename);
unlink($tempfilename);

, generate.php
index.html controller.php.

284

generate.php , r e c e n t j o k e s (
, http://localhost/recentjokes/).
index.html.
, _____________
Mac OS X Linux ,

. ,
, ,
. ,
chmod.
chmod 777 ///recentjokes/

,
PHP- ,
-.

, generate.php
.
, ,
.
, ,
, .
,
generate.php ,
. W indows php.exe ( ,
W indows)
.
generate.bat ( c h a p t e r l 2 / r e c e n t j o k e s /
g e n e r a te .b a t) .
@C:\xampp\php\php.exe generate.php

, ,
, generate.bat .
Mac OS X Linux
c ro n , .
man on t a b ,
.
, Mac OS X Linux,
Windows. ,
c r o n (
/Applications/MAMP/bin/php/php5.3.6/bin/php). generate.php,
on t a b .
0-23 * * * /Applications/MAMP/bin/php/php5.3.6/bin/php ///
generate.php > /dev/null

285

12


, , .
,
.
H TM L-,
. input
type= "file".
. ,
form enctype= "multipart / form-data".
<form tion="index.php" m e t h o d = " p o s t "
enctype="multipart/form-data">
<divxlabel
<input
<div>
< i n pu t
<input
</div>
</form>

for= " u p l o a d " > S e l e c t

type="file"

id="upload"

type="hidden"

fil e to up l o a d :
name="upload"></labelx/div>

name="action"

value="upload">

t y p e = "s u b m i t " v a l u e = "S u b m i t ">

, P H P - ( index.php)
, .
$_FILES, . , ,
$_FILES [ ' upload ' ] (
input), .
$_FILES [ ' u plo a d ' ] , .
,
.
$_FILES [ 'u p lo a d ' ] [ ' tmp_name ' ] . ,
- (
, upload_tmp_dir php.ini).
, P H P -,
.
(, ),
, ,
.
$__FILES [ ' u p lo a d ' ] [ ' name ' ] . , ,
, .

, .
$_FILES [ ' u p lo a d ' ] [ ' size ' ] . ( ).
$_FILES [ ' upload' ] [ ' type ' ] . M IM E- .
, . ,
, text/plain, image/png . .

, ' u p l o a d ' input,


.
.

286

,
. , , , ,
JPEG, , , GIF PNG.
M IM E- image/ jpeg, image/gif image/png . -
1
( , 8).
if (preg_match('/^imageX/p?jpeg$/i1, $_FILES['upload'][1type']) or
preg_match('/Aimage\/gif$/i', $_FILES['upload1]['type']) or
preg_match('/^image\/(x-)?png$/i', $_FILES['upload']['type']))

{
: .

}
else

{
$error = ', JPEG, GIF
PNG.';
include $_SERVER['DOCUMENT_ROOT'] . /includes/error.html.php';
exit();

}

, $_FILES ['upload'] ['size '],
. , ,
.

, :
, .

. .
upload_max_f ilesize php.ini.
2 .
, 2.
.
input MAX_FILE_SIZE
, .
,
upload_max_f ilesize php.ini.
.
1 (1024 ).
<form action="upload.php" method="post"
enctype="multipart/form-data">
<p><label id="upload"> :

1 MIME- . Internet Explorer


JPEG PNG image/ jpeg image/-png, Firefox
image/ jpeg image/png.
2 php.ini post_max_size,
, .
8 , - ,
.

287

12
<input
<input
<P>
<input
<input
</p>
</form>

type="hidden" name="MAX_FILE_SIZE" value="1024">


type="file" id="upload" name="upload"></labelx/p>
type="hidden" name="action" value="upload">
type="submit" value="">

, MAX_FILE_SIZE
i n p u t t y p e = " f i l e ",
, - .
, ,
MAX_FILE_SIZE.
, - u p lo a d _
m ax_f i l e s i z e php.ini.
,
. $_FILE [ ' u p l o a d 1]
[ ' ' ], ,
.
.
, ,
.
( tim e ) ,
, 1
1970 .
? , 1-
, $_SERVER [ ' REMOTE_
A D D R ']. ,
IP.
// .
if (preg_match('/^imageX/?jpeg$/i', $_FILES['upload']['type']))

{
$ext = '.jpg';

}
else if (preg_match('/^imageX/gif$/i', $_FILES['upload']['type']))

{
$ext = '.gif';

}
else if (preg_match('/'/(x-)?png$/i',
$_FILES['upload']['type']))

{
$ext = '.png';

}
else
$ext = '.unknown';

}
//
$filename = ' :/uploads/' . time()

. $_SERVER['REMOTE_ADDR'] . $ext;

// ( ).

288


if (!is_uploaded_file($_FILES['upload'][1tmp_name']) or
'copy($_FILES['upload']['tmp_name'], $filename))

{
$error = "He $filename!";
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit();

>

is_uploaded_f ile, , . TRUE
, , (
$_FILES [' upload1] [' tmp_name1]), .
/etc/passwd (
Linux),
is_uploaded_f ile, $_FILES [ 'upload' ]
,
, .
, , , ,
, is_uploaded_f ile.

is_uploaded_f ile if.
is_uploaded_f ile ($_FILES [ 'upload' ] [ 'tmp_name' ] ) FALSE (
! is_uploaded_f ile ( $_FILES [ ' upload ' ] [ ' tmp_name ' ] ) TRUE), to
PH P , (
or), , , .
, is__uploaded_f ile FALSE, .
is_uploaded_f ile TRUE,
, ,
. or and, FALSE
.
if , .
, while for.
, : Windows,
( / ) Unix.
, ( \ \ ) ,
.
, Windows.
( / )
, .



JPEG, GIF PNG .
,
, , .
9, ,

, , .

289

12

M ySQL
. , ,
(Binary Large Objects, BLOB).
- .
, ,
,
.
.
, ,
. , SQL-,
. ,
SitePoint.
(,
), MySQL .
, MySQL
, ,
.


, -,
. ,
.
CREATE DATABASE filestore

( MySQL-
), .
, M IM E- (, im a g e /
j p e g JP E G ),
. CREATE TABLE
( c h a p t e r l 2 / s q l / f i l e s t o r e . s q l , ).
CREATE TABLE filestore (
id INT NOT NULL PRIMARY KEY AUTO__INCREMENT,
filename VARCHAR(255) NOT NULL,
mimetype VARCHAR(50) NOT NULL,
description VARCHAR(255) NOT NULL,
filedata MEDIUMBLOB
) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB

.
MEDIUMBLOB. , , MEDIUMBLOB
MEDIUMTEXT ,
. MySQL
:
, . MySQL
,
.

290

, MEDIUMBLOB,
, . ,
,
. MEDIUMTEX
, , .
MEDIUMBLOB BLOB-,

.
: ,
, ,
(. 12.1).
12.1. , MySQL

TINYBLOB
BLOB
MEDIUMBLOB
LONGBLOB


255

,
+ 1

65

+ 2

16,7

+ 3

4,3

+ 4

,
16,7 . ,
, filedata LONGBLOB.
(
MySQL, ),
4,3 (, ,
).
, ,
, db.inc.php
(chapterl2/f ilestore/db. inc .php).
<?php
try

{
$pdo = new PDO('mysql:host=localhost;dbname=filestore1,
'filestoreuser', 'ssword');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES ''utf8'");

}
catch (PDOException $e)

{
$error = 'He .';
include 'error.html.php';
exit();


, ,
,
.
: .

291

12

(chapterl2/ filestore/files .
h t m l .php, ).
<form action="" method="post" enctype="multipart/form-data">
<div>
clabel for="upload">3 :
cinput type="file" id="upload" name="upload"></label>
</div>
<div>
<label for="desc">OnncaHne :
<input type="text" id="desc" name="desc"
maxiength="2 55"></label>
</div>
<div>
<input type="hidden" name="action" value="upload">
cinput type="submit" value="">
</div>
</form>

,
$_FILES [ 'u p l o a d '] [ 1tmp_name '].
$_FILES [ ' u p l o a d 1] [ ' name ' ] (
), $_FILES [ ' uplo a d ' ] [ ' size ' ] ( )
$_FILES [ ' upload ' ] [ ' type ' ] (M IM E - ).
:
,
INSERT. ,
is_uploaded_f ile ,
(chapter 12 / fi lest ore /index.php, ).
<?php
include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/magicquotes.inc.php';
if (isset($_POST['action']) and $_POST['action'] == 'upload')

{
// ,
if (!is_uploaded_file($_FILES['upload']['tmp_name']))

{
$error = ' !';
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit();

}
$uploadfile
$uploadname
$uploadtype
$uploaddesc
$uploaddata

=
=
=
=
=

$_FILES['upload']['tmp_name'];
$_FILES['upload']['name'];
$_FILES['upload']['type'];
$_POST['desc'];
file_get_contents($uploadfile);

include 1d b .inc.p h p ';


try

{
$sql = 'INSERT INTO filestore SET

292


filename = :filename,
mimetype = :mimetype,
description = :description,
filedata = :filedata';
$s = $pdo->prepare($sql)?
$s->bindValue(':filename', $uploadname);
$s->bindValue('rmimetype', $uploadtype);
$s->bindValue(':description1, $uploaddesc);
$s->bindValue(':filedata', $uploaddata);
$s->execute();

}
catch (PDOException $e)

{
$error = ' !';
include $_SERVER[1DOCUMENT_ROOT'] . '/includes/error.html.p h p ';
exit () ;

}
header('Location: . ') ;
exit();


, : ,
.
- .
.
:
.
, :

;
, :
-, ,
;
, ,
, .
-,
. ,
- h e a d e r .
,
, -
.
C o n t e n t - l e n g t h ( c h a p t e r 1 2 /
f i l e s t o r e / i n d e x . php, ).
header('Content-length:

' . strlen($filedata));

293

12

s t r l e n , .
( ),
.
C o n t e n t - t y p e ( c h a p t e r l 2 / f i l e s t o r e /
i n d e x . php, ).
header("Content-type: $mimetype");

, C o n t e n t - d i s p o s i t i o n .
header("Content-disposition: inline; filename=$filename");


.
include 'd b .inc.p h p ';
try

{
$sql = 'SELECT filename, mimetype, filedata
FROM filestore
WHERE id = :id ';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_GET['id']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' .';
include $__SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit();

}
$file = $s->fetch();
if (!$file)

{
$error = ' id !';
include $_SERVER['DOCUMENT__ROOT'] . '/includes/error.html.php';
exit();

}
$filename = $file['filename'];
$mimetype = $file['mimetype'];
$filedata = $file['filedata'];
header('Content-length: ' . strlen($filedata));
header("Content-type: $mimetype");
header("Content-disposition: inline; filename=$filename");
echo $filedata;
exit();

,
, . -

294

Content-disposition inline attachment.


. ,
$_GET [ action ' ] ' download ':
, .
include 'db.inc.php1;
try

{
$sql = 'SELECT filename, mimetype, filedata
FROM filestore
WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_GET['id']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' .';
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit();

}
$file = $s->fetch();
if (!$file)

{
$error = ' id !';
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit();

}
$filename = $file['filename];
$mimetype = $file['mimetype'];
$filedata = $file['filedata'];
$disposition = 'inline';
if ($_GET['action'] == 'download')

{
$disposition = 'attachment';

>
header('Content-length: ' . strlen($filedata));
header(Content-type: $mimetype");
header("Content-disposition: $disposition; filename=$filename");
echo $filedata;
exit();

, Contentdisposition. , ,
Cont ent-type, Contentdisposition.
,
, Cont ent-type Content-disposition
M IM E- appl icat ion/

295

12

o c t e t - s t r e a m , ,
( c h a p t e r 12 / f i l e s t o r e / i n d e x . php, ).
include 'db.inc.php';
try

{
$sql = 'SELECT filename, mimetype, filedata
FROM filestore
WHERE id = ;id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_GET['id ']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' .';
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit();

}
$file = $s->fetch();
if (I$file)

{
$error = ' id !';
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit();

}
$filename = $file['filename'];
$mimetype = $file['mimetype'];
$filedata = $file['filedata'];
$disposition = 'inline';
if ($_GET['action'] == 'download')

{
$mimetype = 'application/octet-stream';
$disposition = 'attachment';

}
// Content-type Content-disposition
header('Content-length: ' . strlen($filedata));
header("Content-type: $mimetype");
header("Content-disposition: $disposition; filename=$filename");
echo $filedata;
exit();


.
, ,
, ,
.

296

( c h a p t e r l 2 / f i l e s t o r e / i n d e x . php).
<?php
include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/magicquotes.inc.php';
if (isset($_POST['action']) and $_POST['action'] == 'upload')

{
// , ,
if (!is_uploaded_file($_FILES['upload']['tmp_name']))

{
$error = ' !';
include $_SERVER['DOCUMENT_ROOT'] . 1/includes/error.html.php';
exit();

}
$uploadfile
$uploadname
$uploadtype
$uploaddesc
$uploaddata

=
=
=
=
=

$_FILES['upload']['tmp_name'];
$_FILES['upload']['name'];
$_FILES['upload']['type'];
$_POST['desc'];
file_get_contents($uploadfile);

include 'd b .inc.p h p ';


try

{
$sql = 'INSERT INTO filestore SET
filename = :filename,
mimetype = :mimetype,
description = :description,
filedata = :filedata';
$s = $pdo->prepare($sql);
$s->bindValue(':filename', $uploadname);
$s->bindValue(':mimetype', $uploadtype);
$s->bindValue(':description', $uploaddesc);
$s->bindValue(':filedata', $uploaddata);
$s->execute();

}
catch (PDOException $e)

{
$error = ' !';
include $_SERVER['DOCUMENT_ROOT'] . /includes/error.html.p h p ';
exit();

}
header('Location: .');
exit();

}
if (isset($_GET['action']) and
($_GET['action'] == 'view' or $_GET['action'] == 'download') and
isset($_GET[id']))

{
include 'd b .inc.p h p ';
try

f
$sql = 'SELECT filename, mimetype, filedata

297

12
FROM filestore
WHERE id = :id ';
$s = $pdo->prepare($sql) ;
$s->bindValue(':id', $_GET['id ']);
$s->execute();

}
catch (PDOException $e)

{
$error = ' .';
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit();

$file = $s->fetch();
if (! $file)

{
$error = ' id !';
include $__SERVER ['DOCUMENT_ROOT'] . '/includes/error.html.php';
exit();

$filename = $file['filename'];
$mimetype = $file['mimetype'];
$filedata = $file['filedata'];
$disposition = 'inline';
if ($_GET['action'] == 'download')

{
$mimetype = 'application/octet-stream';
$disposition = 'attachment';

}
// Content-type Content-disposition.
header('Content-length; ' . strlen($filedata));
header("Content-type: $mimetype");
header("Content-disposition; $disposition; filename=$filename");
echo $filedata;
exit();

}
if (isset($_POST['action']) and $_POST['action'] == 'delete' and
isset($_POST['id']))

{
include 'db.inc.php';
try

{
$sql = 'DELETE FROM filestore
WHERE id = ;id';
$s = $pdo->prepare($sql);
$s->bindValue(':id '# $_POST('id']);
$s->execute();

catch (PDOException $e)

V
$error = ' .';

298


include $_SERVER[1DOCUMENT_ROOT1] . '/includes/error.html.php';
e x i t ();

}
h e a d e r (1Locat i o n : . ') ;
e x i t ();

}
include

'db.inc.php';

try

{
$result = $pdo->query(
'SELECT id, filename, mimetype, description
FROM filestore');

>
catch

(PDOException $e)

{
$error = ' .';
include $_SERVER['DOCUMENT_ROOT'] . '/includes/error.html.php';
e x i t ();

}
$ files = a r r a y O ;
foreach ($result as $row)

{
$files[] = a r r a y (
'id' => $row['id.' ] ,
'filename' => $ r o w ['filename'],
'mimetype' => $r o w ['mimetype'],
'description' => $row['description']);

include 'files.html.php';

,
(c h a p te r1 2 /f ile s to r e /f ile s .h tm l.p h p ) .
<?php include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/helpers.inc.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=''utf-8''>
<title>Peoop PHP/MySQL</title>
</head>
<body>
<1> PHP/MySQL</hl>
<form action="" method="post" enctype="multipart/form-data">
<div>
clabel for="upload">3 :
<input type="file" id="upload" name="upload"></label>
</div>
<div>
<label for="desc">Oroicaraie :
<input type="text" id="desc" name="desc"

299

12
maxlength="255"></label>
</div>
<div>
<input type=" hidden" name =" act ion" value= "upload" >
cinput type="submit" value="">
</div>
</form>
<?php if (count($files) > 0 ) :

?>

<p>B :</>
<table>
<thead>
<tr>

<th>HMn aa</th>
<th>Tnn</th>
<th>OnncaHne</th>

</tr>
</thead>
<tbody>
<?php foreach($files as $f): ?>
<tr>
<td>
<a href="?action=view&amp;id=<?php htmlout($ f ['id']); ?>"
><?php htmlout($ f ['filename1]); ?></a>
</td>
<tdx?php htmlout ($f ['mimetype']) ; ?></td>
< tdx?php htmlout ($f ['description']); ? x / t d >
<td>
<form action="" method="get">
<div>
<input type="hidden" name="action" value="download"/>
<input type="hidden" name="id" value="<?php
htmlout($ f ['id']); ?>"/>
<input type="submit" value=""/>
</div>
</form>
</td>
<td>
<form action="" method="post">
<div>
<input type="hidden" name="action" value="delete"/>
<input type="hidden" name="id" value="<?php
htmlout($f['id']); ?>"/>
<input type="submit" value=""/>
</div>
</form>
</td>
< /tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</body>
</html>

300
*

, ( c h a p t e r 12 /
f i l e s t o r e / d b . i n c .p h p ).
<?php
try
$pdo = new PDO('mysql:host=localhost;dbname=filestore',
'filestoreuser', 'mypassword');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES mutBm');
catch (PDOException $e)

{
$error = 'He .';
include 'error.html.p h p ';
exit();

, ( f i l e s t o r e )
( f i l e s t o r e u s e r ) , .
f i l e s t o r e i j d b
, ,
db.inc.php.
,
, .
. 12.1.


/MySQL
:
:

..........

.............

. 12.1.

301

12

(. 12.2).
^

PHP/MvSOL - Mozilla Firefox


.............. . ^
...' .................. I v
<3<0
localhost/filestore/

I 3 i* |||

*.

___
v
] 1&

00v


/MySQL
:
:

Browse..

: :

,
phpmysql5.pdf application pdf .
, ?
Test.txt

text/plain

. 12.2.
, ( ,
).
, . ,
.
,
MySQL.
. ,
,
,
, .
, ,
.


, , ,

. ,
.

MySQL
M ySQL (),
1 . ,

302

. ,
1
UPDATE, INSERT.
, m ax _ al lo w ed _
p a c k e t my.cnf my.ini.
MySQL (http://dev.mysql.eom/doc/refman/5.1/
en/packet-too-large.htmI).


,
8 .
,
, , , ,
. , php.ini
, m e m o ry _ lim it.


, 30 .
, ,
.
s e t _ t im e _ lim it, ,
, ,
, .
, ,
.



, MySQL.
, :
MySQL,
, .
( ,
)
, .
.
, -,
, ,
. .

(http://php.net/docs.php).

MySQL
: ,
;

303

12

. ,
, -
. , ,
MySQ. !

SitePoint : ( Master:
W rite Cutting-edge Code; ht^://www.sitepoint.com/books/phppro1/).
, ,
, -
.
, ,
.
,
, Zend Framework (http:^ramework.zend.
com/), C akePH P (http://cakephp.org/) Symfony (http://www.symfony-project.org/).

. ,
P H P -.
,
, .
, . ,
, . ,
,
.
,
,
. .
? - !



MySQL

1 -
M ySQL , .
,
, ,
.
,
MySQL , , ,
.
Windows, Mac OS X Linux.

Windows
MySQL
M ySQL . ,
MySQL ( http://dev.mysql.com/downloads/)
MySQL Community Server Download.
MySQL (
5.5.22).
32- 64- Windows.
, 64- , Download
W indows (86, 64-bit), MSI Installer ( 33 ).
32- Windows,
W indows (86, 32-bit), MSI Installer ( 31 ),
64- .
,
.
Typical (
, ).
,
MySQL (Instance Configuration W izard), Detailed Configuration.
, .
.

305

(Server type). , MySQL


, Developer Machine.
(Database usage).
, ,
Multifunctional Database.
InnoDB (InnoDB tablespace settings).
.
, MySQL.
, .
(Connection limit).
Decision Support (DSS)/0LAP, MySQL
.
(Networking options). Enable
Strict Mode, MySQL
, .
(Default character set). Best Support
For Multilingualism. MySQL , ,
UTF-8, ,
-.
Windows (W indows options).
MySQL Windows, .
Include Bin Directory in Windows PATH,
MySQL .
(Security options). r o o t
,
, MySQL.
.
,
MySQL.
, MySQL .
Ctrl+Alt+Del .
( ).
, , mysqld.exe,
.


. http://windows.php.net/
download/ . 5.4.x Windows VC9 Non
Thread Safe VC9 Thread Safe. , .
Apache.
VC9 Thread Safe zip.


, Apache IIS,
-.

306

MySQL

Windows - IIS.
Windows Home, Windows Vista Home, Windows 7 Home
Basic .
, - .
, IIS
.
IIS, , ,
- .
Linux,
Apache. IIS
, Windows,
, ASP.NET Microsoft,
IIS,
-.
,
, (
). - Apache,
Windows.
, , P H P -
IIS, install.txt
zip-, .
Apache, Apache Lounge (http://www.apachelounge.
com/) (
2.4.1).
zip-,
, .
,
. ,
Microsoft Visual C++ Redistributable Package.
,
.
, Apache24,
zip-, :, Apache
C:\Apache24. ,
,
, .
Apache
, ,
. , ,
, ,
. ,
.
:\Windows\system32>

. :
Enter, , .

307

c d \ A pache2 4 \ b i n Enter,
C:\Apache24\bin.
:\Windows\system32 >:
:\Windows\system32>cd \Apache24\bin
:\Apache24\bin>

Apache, httpd.exe Enter.


:\Apache24\bin>httpd.exe

, , :
, .
, .
:\Apache24\bin>httpd.
(OS 10013)An attempt was made to access a socket in a way forbidden
by its access permissions. : AH00072: make_sock: could not bind to
address [:s]:80(OS 10013)An attempt was made to access a socket in a way
forbidden by its access permissions. : AH00072: make_sock: could not bind
to address 0.0.0.0:80AH00451: no listening sockets available, shutting
downAH00015: Unable to open logs
:\Apache2 4\bin>

Apache ,
-, 80-
-. , IIS Apache,
. , ,
Apache .
, , http://localhost
Enter. . .1 ,
Apache.

It works!
. .1. Apache
. Apache,
Ctrl+C. .

308

MySQL
:\Apache2 4\bin>httpd.exe
:\Apache24\bin>

, ,
Apache. h t t p d . e x e -k i n s t a l l ,
Apache .
.
:\Apache24\bin>httpd.exe -k install
Installing the Apache2.4 service
The Apache2.4 service is successfully installed.
Testing httpd.conf....
Errors reported here must be corrected before the service can be started.

, .
:\Apache24\bin>httpd.exe -k install
Installing the Apache2.4 service
(OS 5)Access is denied. : AH00369: Failed to open the WinNT service
manager, perhaps you forgot to log in as Adminstrator?yoss

,
,
. ,
.
Apache ,
C:\Apache24\bin, .
ApacheMonitor.exe.
-, .
( )
. Apache Monitor.
, .
, Apache2.4.
, Start, Stop
Restart. Apache, Start.
, - (. .2).

. .2. ,
Apache

-, Apache,
.
, Apache , .
.

309

1. , .
C:\php, ,
, .
2. php.ini-development
. ,

. php - Copy.ini-development
( Windows, ).
php.ini.
( .ini-dist .ini)? .

JJ

WINDOWS
___________________________________________________________
php.ini, ,
php. , Windows
. ,
.ini ,
.
.
php.ini, php.gif
php.exe, ,
.
,
Windows .

(. .).

1]
W...1


.
, . "" "".
.

:
(10 NTI
i "
0
# &
,
( ""


,
,

I j

. .. ,

310

MySQL

3. php.ini.
, , .

.
, d o c _ r o o t (
).
doc_root =

-.
Apache htdocs,
, .
, C:\Apache24\htdoc.
, htdocs .
doc_root = "C:\Apache24\htdocs"

,
; e x t e n s i o n _ d i r .
ext -.
extension_dir = "C:\php\ext"

, ,
; e x t e n s i o n s
, . ,
MySQL.
p h p _ m y s q li . d l l .
extension=php_mysqli.dll

. HE PHP_MYSQL_________________________________________
p h p _ m y s q li . d l l p h p _ m y sq l . d l l .
/ im p ro v e d ().
. / ,
MySQL.

, ; s e s s i o n .
s a v e _ p a t h . ,
,
Windows.
session.save_path = "C:\Windows\Temp"

.
.
Apache ,
.
1. ( )
. conf ,

311

Apache ( C:\Apache24\conf), httpd.conf.


,
(*.*).
2. , Directorylndex.
<IfModule dir_module>

Directorylndex index.html
</IfModule>

Apache ,
.
index.php.
<IfModule dir_module>

Directorylndex index.html index.php


</IfModule>

3.

. .
LoadModule php5_module ":/php/php5apache2_4.d l l "
AddType application/x-httpd-php .php
PHPIniDir "C:/php"

, LoadModule PHPIniDir
, , ,
, .
^

APACHE______________________________________________
, A pache
.dll-, LoadModule,
Apache . ,
Windows php5apache2_4.dll.

, , ,
, php5apache2_2.dll php5apache2_3.dll.
Apache 2.2 2.3 . ,
, Apache
, .dll-. , Apache 2.5
php5apache2_5.dll.
,
Apache, Apache Lounge
(http://www.apachelounge.com/download/). , , php5apache2_4.
dll-php-5.4-win32.zip. zip-, . d l l -
, . Apache ,
LoadModule.

4. .
5. Apache Apache M onitor
. , Apache - .
,
.

312

MySQL

. ,
httpd.conf.

6. Apache Monitor, Apache Service


Monitor. ,
(. .4).

Stop
Restart
Services
^

Connect
Disconnect

Apache/2.4.1 (Win32) /5.4

. A4. PHP ,
Apache
7. Apache Service Monitor, .

, MySQL, Apache ,
-.

Mac OS X
,
Mac OS X 10.6 (Snow Leopard) .
OS X,
.

MySQL
MySQL (http://dev.mysql.com/
downloads/) Download MySQL Community Server.
MySQL
( 5.5.22), . .5.

. ,
64- , Mac OS X ver. 10.6 (86, 64-bit), DM G
Archive. , Mac OS X ver. 10.6

313

(86, 32-bit), DM G Archive, Intel . ( ,


, Apple.) 32-
,
64- .
Generally Available (GA) Releases

MySQL Community Server 5.5.22


Looking for previous GA
versions?

jM it O S X

Select

titii : i i

m.1

Mae OS X ver. 10.6 (x86, 64-btt), Compressed


TAR Archive
(my*-S.S.22'Kl0.e-xa6jS4.tr.st>
Mac OSX ver. 10.6 (, 32-bh), compressed
TAR Archive

1 1 1 i i I

mm
5.5.22
w

MDS
* . (77!.0412923 | Signature

8.5.22

<m ysq.S.S.2J-xl0.6-x86,t*(\gz>

Mac OS X ver. 10.6 (x86,32-bit), DMG Archive

M05: 23001

5.5.22

{Biyeqi'S.S.22-oe*10.S**86.dmg>
o s x ver. . (, 64-bft), dmg Archive
(*-$.5.22-*10.-*6,*>

uo.SM
i . s

jjg jg g
|

SSsnWw*

109.7M

: 132*!237(0042 | enrture
5.5.22

m.6M

CSSSSQI

MD5i Sc212*jS6W$M*c11iVXTtASUTb* | Signature

. A .5. 32- MySQL Intel-


mysql --., ,
. . .6,
.pkg, MySQLStartupltem.pkg. ,
MySQL.

. .6. MySQL Mac OS X


, MySQL. 1
.
M a c h i n e user$ sudo /usr/local/mysql/bin/mysqld_safe

1 , ,
.

314

MySQL


M a c h in e :~

user$, M a c h i n e
,
, .
, .

, Enter.
mysqld_safe, ,
. ,
MySQL .
MySQL .
Ctrl+Z, ,
, :
M a c h i n e user$ bg

, MySQL
. MySQL,
.
Machine:

user$ sudo /usr/local/mysql/bin/mysqladmin shutdown

MySQL-
. (. . .6),
MySQL.pref. ,
(. .7).

MySQL Server Status


The MySQL Database Server is started and ready for ciient connections.
To shut the Server down, use the 'Stop MySQL Server* button.

The MySQL Server Instance is

Stop MySQL Server j

if you stop the server, you and your applications will not
be able to use MySQL and all current connections will be dosed.

0 Automatically Start MySQL Server on Startup

... .

You may select to have the MySQL server start


automatically whenever your computer starts up.

MySQL.
. .7. MySQL

, M ySQL-,
.
,
, MySQL
. .
, ,
MySQLStartupltem.pkg .

315

,
MySQL
.dmg.
, , /usr/local/mysql/bin
. ,
mysqladmin mysql .
.
Machine:~ user$ sudo su
Password: ( )
sh-3.2# echo </usr/local/mysql/bin> >> /etc/paths .d/mysql
sh-3.2# exit

,
. MySQL
mysqladmin .
M a c h i n e u s e r $ mysqladmin status

,
MySQL.


Mac OS X 10.5 (L eopard)
Apache 2.2 5. , , .
1. Apple.
2. .
3. , -
(. .8)

* ,
; Name.local

. ;

DVO

. .8. - Mac OS X

316

MySQL

4. .

5. , http://localhost
Enter. Apache
(. .9).

I t w orks!

i
. .9. Apache

, Apache
. ,
.
1. Finder (ft+36+G),
/ p r i v a t e / e t c / a p a c h e 2 / .
2. Finder httpd.conf,
Apache.
.
(36+1).
.

.
, (. . 10)
.

X . system

. . 10. ,

317

httpd.conf, everyone (. .11).


:
:

JL system
I t wheel

. .11. everyone
3. Finder, apache2.

.
everyone .
4. , httpd.conf,
TextEdit.
5. .
#LoadModule php5_module

Iibexec/apache2/libphp5.so

, (# ) .
6. .
7.
httpd.conf apache2.
Apache.
8. Apache.
.
M a c h i n e u s e r $ sudo /usr/sbin/apachectl restart

.
9. http://localhost , Apache

. , .
,
. /var/log apache2 error log,
Apache
. ,
SitePoint.

318

MySQL

- Apache .
,
httpd.conf.
, php.ini. ,
, MySQL.
, Mac OS X,
php.ini. . ,
/private/etc/php.ini.default
/private/etc/php.ini.
M a c h i n e u s e r $ cd /private/etc
Machine:etc user$ sudo cp php.ini.default php.ini
Password: ( )

,
, httpd.conf. Finder
, /private/etc, php.
ini , ,
TextEdit.
( +F )
m y s q l . d e f a u l t _ s o c k e t . ,
.
mysql.default_socket = /tmp/mysql.sock

,
.
, m y sq l i . d e f a u l t _ s o c k e t (m y sq l i,
m y sq l), .
mysqli.default_socket = /tmp/mysql.sock

, TextEdit
.
Apache .
M a c h i n e u s e r $ sudo /usr/sbin/apachectl restart

. Apache ,
h t t p : / / l o c a l h o s t .
. , MySQL, Apache ,
.

Linux
Apache, MySQL
Linux.
U buntu 10.04.4 (http://www.ubuntu.com),

319

, Fedora (http:^edoraproject.org), Debian (http://www.debian.org),


openSUSE (http://www.opensuse.org) Gentoo (http://www.gentoo.org).
.
Linux
. Synaptic (https://help.ubuntu.com/community/SynapticHowto),
Ubuntu, APT (http://www.debian.org/
doc/user-manuals#apt-howto) Debian.
RPM. , , Linux
, Apache, MySQL.
, , .
, .
, ,
Linux ,
.
Apache, MySQL,
.
.

MySQL
MySQL. (http://
dev.mysql.com/downloads/) Download MySQL Community
Server.
MySQL ( 5.5.22).
, Linux Generic. ,
. , 64- Linux,
Linux Generic 2.6 (86, 64-bit), Compressed TAR Archive (
177 ). 32- Linux Generic 2.6 (86,32-bit),
Compressed TAR Archive ( 171 ), ,
64- . Download ,
.
,
.
. user$machine:~$ sudo su

, .
/usr/local .
root@machine:/home/user# cd /usr/local
rootmachine:/usr/local# tar xfz ~user/Desktop/mysql-version-linux2.
6-platform.tar.gz

,
, Desktop . u s e r
, v e r s i o n MySQL,
p l a t f o r m ,

320

MySQL

.
. ,
.
root@mythril:/usr/local# tar xfz ~kyank/Desktop/mysql-5.5.
22-linux2.6-x86_64.tar.gz

.
I s ,
mysql-version-linux-platform. .
root@mythril:/usr/local# Is
bin games
lib m y s q l - 5 . 5 .2 2 - l i n u x 2 . 6 - x 8 6 _ 6 4 share
etc include man sbin
src

,
m y sq l. .
r o o t Q m a c h i n e : /usr/local# In -s mysql-version-linux-platform mysql
rootmachine:/usr/local# cd mysql

MySQL
(, MySQL ), ,
, .
, MySQL.
, (
).
root@machine:/usr/local/mysql# groupadd mysql
root@machine:/usr/local/mysql# useradd -g mysql mysql

mysql.
root@machine:/usr/local/mysql# chown -R mysql .
rootmachine:/usr/local/mysql# chgrp -R mysql .

M ySQL-. ,
, .
, mysql.
root ^ m a c h i n e : /usr/local/mysql# scripts/mysql_install_db --user=mysql

, libaio.so,
. U buntu Linux
apt-get.
rootmachine:/usr/local/mysql# apt-get install libaiol
root^ m a c h i n e : /usr/local/mysql# scripts/mysql_install_db --user=mysql

M ySQL- .
, .
r o o t & m a c h i n e : /usr/local/mysql# bin/mysqld_safe --user=mysql &

321

mysql daemon ended, ,


MySQL . hostname.err
date, hostname .
- , MySQL.
MySQL , ,
FTP -, , . ,
MySQL ,
.
r o o t & m a c h i n e : /usr/local/mysql# bin/mysqladmin -u root status


MySQL.
hostname.err.
,
, , SitePoint (http://
www.sitepoint.com/forums/). .
, MySQL
, . support-files
mysql mysql.server,
. Linux
/etc/init.d mysql.server,
/etc/rc2.d/S99mysql /etc/rcO.d/K01mysql.
r o o t Q m a c h i n e : /usr/local/mysql# cd /etc
r o o t Q m a c h i n e : /etc# In -s /usr/local/mysql/support-files/mysql.server

init.d/
r o o t & m a c h i n e : /etc# In -s /etc/init.d/mysql.server rc2.d/S99mysql

rootmachine:/etc# In -s /etc/init.d/mysql.server rcO.d/K01mysql

. , ,
mysqladmin,
.

root. bin/mysql_secure_installation.
root^ m a c h i n e : /usr/local/mysql# ./bin/mysql_secure_installation

S fe

HE TEST?
, mysql_securejnstallation test.
MySQL Linux,
.empty data/test, test. MySQL
, , .
, MySQL .

M ySQL-,
, .
mysql, mysqladmin mysqldump
/usr/local/bin.

322

MySQL
rootmachine:/etc# cd /usr/local/bin
rootmachine:/usr/local/bin# In -s /usr/local/mysql/bin/mysql .
root@machine:/usr/local/bin# In -s /usr/local/mysql/bin/mysqladmin .
root@machine:/usr/local/bin# In -s /usr/local/mysql/bin/mysqldump .

,
. M ySQL-
.
root@machine:/usr/local/bin# exit
user@machine:~$ mysqladmin -u root -p status

PHP
,
-, . Apache
:
C G I-, Apache ,
-;
, Apache;
, Apache.
, ,
-.
-,
.

. ,
Apache
. .
-
, sudo apt-get
install apache2 Ubuntu Linux, Apache H T T P
Server (http://httpd.apache.org/) Apache
( 2.4.4).
,
. Unix Source (. . 12).
.tar.gz .tar.bz2 , ,
.
, , Apache.
.
, ,
.
user@machine:~$ cd Desktop
userQmachine:~/Desktop$ tar xfz httpd-version.tar.gz
userQmachine:~/Desktop$ cd httpd-version

323

Apache HTTP Server 2.4.4 (httpd): 2.4.4 is the latest available version

2.4

The Apache HTTP Server Project Is pleased to announce the release of version
GA release of the new generation 2.4.x branch of Apache HTTPD and represents fH
For details see the . and the CHANGES 2.4 and CHANGES 2
Unix Source: httDd-2.4.4 tar.bz2 ^ G P
Unix Source:

W&2AA.MM

]f MD5 ] [SHA1)
] [5 ]

NetWare Binary: httpd 2.4.4- ^ ^ ^

] f MD5 ] j SHA1}

* ^M.dty..and..Qlial..K!.tc.bfi

. mes

. A .12. ,

Apache,
.
,
, , . ,
, , URL,
,
.
, .
u s e r Q m a c h i n e : -/Desktop/httpd- v e r s i o n $

./configure --enable-so --enable-

rewrite

. ,
, ,
Apache. Linux
.
, . Ubuntu,
, .
.
config.status: creating build/rules.mk
config.status: creating build/pkg/pkginfo
config.status: creating build/config_vars.sh
config.status: creating include/ap_config_auto.h
config.status: executing default commands
u s e r @ m a c h i n e : -/Desktop/httpd- v e r s i o n ^

Apache.
make.
u s e r Q m a c h i n e : -/Desktop/httpd- v e r s i o n ^ make


.
make[l]: Leaving directory '/home/user/Desktop/httpd-v e r s i o n '
u s e r Q m a c h i n e : -/Desktop/httpd- v e r s i o n ^

324

MySQL

Apache,
sudo make install (sudo ,
).
u s e r Q m a c h i n e : ~/Desktop/httpd-version$ sudo make install

.
Apache , .
Apache
apachectl:
u s e r Q m a c h i n e : ~/Desktop/httpd-version$ cd /usr/local/apache2
u s e r Q m a c h i n e : /usr/local/apache2$ sudo bin/apachectl -k start

, , Apache
. :
.
Apache
, , ( Ubuntu).
u ser$ m a ch in e:~ $

sudo service apache2 start

http: //localhost.
Apache , (. . 13).

file

Edit

ssji*

yiew
"

v*.

History

'

gookmarks

Iools

fcjel

| ( j ) | http://localhost/

It works!
. A. 13. , A pache

MySQL, ,
Apache , .
Apache , , , .
, MySQL.
apachectl Apache.
u s e r & m a c h i n e : /usr/local/apache2$ sudo su
r o o t & m a c h i n e : /usr/local/apache2# cd /etc
r o o t & m a c h i n e : /etc# In -s /usr/local/apache2/bin/apachectl init.d/

rootmachine:/etc# In -s /etc/init.d/apachectl rc2.d/S99httpd


rootmachine:/etc# In -s /etc/init.d/apachectl rcO.d/K01httpd

, ,
http://localhost.
Apache.
(http://www.php.net/downloads.php)

325

Complete Source Code. , .tar.gz .tar.bz2


, , .
, , php-vers/on.tar.gz ( .bz2).
, ,
.
u s e r Q m a c h i n e : ~$ cd Desktop
u s e r @ m a c h i n e : ~ / D e s k to p $ tar xfz php-version.tar.gz
u s e r Q m a c h i n e : ~ / D e s k to p $ cd php-version

P H P -,
apxs Apache.
, .
,
Apache . ,
Apache. , U buntu
apt-get:
u ser$ m a ch in e:~ $

sudo apt-get install apache2-dev

PH P, :
u s e r Q m a c h i n e : ~ / D e s k t o p / p h p - v e r s i o n $ sudo su
[s u d o ] p a s s w o r d f o r u s e r : ( )
r o o t ^ m a c h i n e : /h o m e /u s e r/D e s k to p /p h p -v e r s i o n #

,
, , MySQL apxs
Apache. ( ).
r o o t ^ m a c h i n e : /h o m e / u s e r / D e s k t o p / p h p - v e r s i o n #

./configure --pref ix=/usr/


local/php --with-apxs2=/usr/local/apache2/bin/apxs --with-mysqli=/usr/
local/mysql/bin/mysql_conf ig

- -prefix ,
(/usr/local/php ).
with-apxs2 , apxs.
, , ,
/usr/bin/. Apache ,
, Apache,
(/usr/local/apache2/bin/).
--with-mysqli ,
MySQL. , mysql_config
bin (/usr/local/mysq l/bin/mysql_config).
.
. ,
Ubuntu 10.04.4 , , ,
Iibxml2. ,
Synaptic, Iibxml2-dev
( Iibxml2 ). ,

326

MySQL

apt-get install libxml2-dev. ,


configure.
,
(Thank
you for using PH P). .
r o o t m a c h in e : / h o m e / u s e r / D e s k t o p / p h p - ve rs io n # make
r o o t m a c h in e : / h o m e / u s e r / D e s k t o p / p h p - ve rs io n # make install

. make install
, /usr/local/php, ,
, - -prefix configure.
.
php.ini.
php.ini-development php.ini-production.
/usr/local/php/lib,
php.ini-development php.ini.
r o o t@ m a c h in e :/h o m e /u s e r /D e s k to p /p h p - version# cp php.ini* /usr/local/php/lib/
r o o t ^machine: / h o m e / u s e r / D e s k t o p / p h p - ve rs io n # cd /usr/local/php/lib
r o o t @ m a c h i n e : / u s r / l o c a l / p h p / l i b # cp php.ini-development php.ini

, ,
.
php.ini .
Apache, .
, conf
Apache (/usr/local/apache2/conf/httpd.conf) /etc/apache2/apache2.conf,
,
. ,
root.
r o o t @ m a c h i n e : / u s r / l o c a l / p h p / l i b # cd /usr/local/apache2/conf
r o o t @ m a c h i n e : / u s r / l o c a l / a p a c h e 2 / c o n f # gedit httpd.conf

, .
Apache , .php
-.
< F ile s M a t c h \ . p h p $ >
S e t H a n d le r a p p l i c a t i o n / x - h t t p d - p h p
< /F ile s M a tc h >

.
Apache.
r o o t@ m a c h in e :/u s r /lo c a l/a p a c h e 2 /c o n f# /usr/local/apache2/bin/apachectl -k restart

, Apache -
. , SitePoint (http:/Avww.sitepoint.
conrVforums/), , .

M ySQL

SQL-,
MySQL 5.5.22 .
:
;
([ ]);
, ,
({}), (|);
, .
, ,
. ,
,
, . ,
, .
, MySQL,
( http://dev.mysql.com/doc/mysql/en/).

A LTER TA B LE
ALTER

[IGNORE]

TABLE tbl_name a c t i o n [ ,

a c t io n ...]

a c t i o n
.
ALTER TABLE
( ,
). ,
.
ADD [COLUMN] c r e a t e _ d e f i n i t i o n [FIRST I AFTER column_name ].
. c r e a t e _ d e f i n i t i o n
, CREATE TABLE,
. ,
,
FIRST AFTER column_name. COLUMN
.

328

MySQL

ADD INDEX [in d e x _ n a m e] ( i n d e x _ c o l _ n a m e , ...) .


,
. inde x_nam e.
, ,
, .
CHAR / VARCHAR,
, ,
i n d e x _ c o l _ n a m e . , myColumn (5)
myColumn.
BLOB TEXT.
ADD FULLTEXT [i n d e x _ n a m e ]
(i n d e x _ c o l _ n a m e ,...) .
.
CHAR, VARCHAR TEXT,
MATCH MySQL.
(:/^.$1./1/81/1111-5.11).
ADD FOREIGN KEY [index_name] (i n d e x _ c o l _ n a m e , ...) r e f e r e n c e _
d e f i n i t i o n .
InnoDB, ,
.

r e f e r e n c e _ d e f i n i t i o n ,
.
REFERENCES t _ {index_col_nam e , ...)
[ON DELETE { RESTRICT I CASCADE
[ON UPDATE { RESTRICT I CASCADE

I SET NULL
I SET NULL

I NO ACTION } ]
I NO ACTION } ]

r e f e r e n c e _ d e f i n i t i o n
ON DELETE ON UPDATE, ,
,
.
MySQL (http://dev.mysql.com/doc/
mysql/en/innodb-foreign-key-constraints.html).
A D D PRIMARY KEY (i n d e x _ c o l _ n a m e , ...) .
PRIMARY ,
. ( ) ,
ADD UNIQUE.
, . i n d e x _ c o l _ n a m e
, ADD INDEX.

ADD UNIQUE [i n de x _n a m e] ( i n d e x _ c o l _ n a m e , ...) .


, (
, ) .
i n d e x _ n a m e i n d e x _ c o l _ n a m e ,
ADD INDEX.
ALTER [COLUMN] c ol_ n a m e {SET DEFAULT v a l u e I DROP DEFAULT}.
(SET DEFAULT)
(DROP DEFAULT ). COLUMN
.

329

CHANGE [COLUMN] c o l _ n a m e c r e a t e _ d e f i n i t i o n .
1_ ,
c r e a t e _ d e f i n i t i o n ( ,
CREATE TABLE).
. ,
c r e a t e _ d e f i n i t i o n ,
.
, : 1_ ,
c r e a t e _ d e f i n i t i o n ,
MODIFY.
DISABLE KEYS ENABLE KEYS.
MySQL .
ALTER TABLE ... DISABLE KEYS,
MySQL . ,
ALTER TABLE ... ENABLE KEYS,
.
.
DROP [COLUMN] col_name.
. .
, ,
. , COLUMN
.
DROP PRIMARY KEY, DROP INDEX index_name DROP FOREIGN KEY
index_name. :
,
.
MODIFY [COLUMN] c r e a t e _ d e f i n i t i o n .
CHANGE.
, .
,
c r e a t e _ d e f i n i t i o n , CREATE
TABLE. , COLUMN .
,
SQL Oracle,
.

ORDER BY col_nam e. .
,
.

,
SELECT. ,
() .
RENAME [ ] n e w _ t b l_ n a m e . .
.
table_options . , CREATE
TABLE,

330

MySQL

,
MySQL (http://dev.mysql.eom/doc/refman/5.5/en/create-table.html).

A N A LY ZE TA B LE
ANALYZE TABLE tbl_n am e [ ,

tbl_name ...]

,
SELECT, .
,
.
.

B E G IN
BEGIN

, START TRANSACTION.

C O M M IT
COMMIT

START TRANSACTION
( ), MySQL
, ,
. COMMIT,
.

C R EATE DATABASE
CREATE DATABASE

[IF

NOT E X IS T S ]

db_name

db_name.
,
.

C R E A T E IN D E X
CREATE

[UNIQUE

I FULLTEXT]

INDEX index_name ON tbl_name

( c o l_

name [ ( le n g th ) ] , ...)

331

.
, ALTER TABLE ADD {INDEX I UNIQUE I FULLTEXT},
ALTER TABLE.

C R EA TE TA B LE
CREATE

[TEMPORARY]

TABLE

[IF

NOT E X IS T S ]

[d b _ n a m e.] tb l_ n a m e

[(c r e a t e _ d e f i n i t i o n , ...) ]
[ ta b le _ o p tio n s]
I L IK E

[[IG N O R E

I REPLACE]

[db_nam e. ] o l d _ tb l _ n a m e

se le c t_ sta te m e n t]

e r e a t e _ d e f i n i t i o n .
{

co l_ n a m e t y p e

[NOT N ULL] [DEFAULT d e f a u l t _ v a l u e ]


[AUTO_INCREMENT] [PRIMARY KEY]

I PRIMARY KEY
I INDEX
I UNIQUE

(i n d e x _ c o l _ n a m e , ...)

[in d ex_ n a m e]
[IN D E X ]

I FULLTEXT

( i n d e x _ c o l _ n a m e , ...)

[i n d e x _ n a m e ]

(i n d e x _ c o l _ n a m e , ...)

[ i n d e x _ n a m e ] \ i n d e x _ c o l _ n a m e , ...)

I FOREIGN KEY
REFERENCES
[ON DELETE
[ON UPDATE

[i n d e x _ n a m e ] (i n d e x _ c o l _ n a m e , ...)
t b l _ n a m e (i n d e x _ c o l _ n a m e , ...)
{ RESTRICT
{ RESTRICT

I CASCADE
I CASCADE

I SET NULL
I SET NULL

| NO ACTION } ]
I NO ACTION } ] }

t y p e (. ), a i n d e x _ c o l _
, ALTER TABLE ADD INDEX,
ALTER TABLE.
CREATE TABLE t b l _
,
db_name. TEMPORARY, ,
, . ,
, ,
,
. .
, ,
TEMPORARY . :
IF NOT EXISTS . ,
.

(. c r e a t e _ d e f i n i t i o n ) .
, .
NOT N U L L .
(NULL). N U L L , , ,

332

MySQL

("). , VARCHAR,
NOT NULL, ' ', NULL.
INT , ,
NULL, .
DEFAULT default_value . DEFAULT
, INSERT
. , ,
NOT NULL, NULL.
DEFAULT,
: ("), (0), ' 0 0 0 0 - 0 0 - 0 0 '
.
AUTO_lNCREMENT . 2,
AUTO_INCREMENT NULL,
, ,
.
NOT NULL ( PRIMARY KEY),
(UNIQUE).
PRIMARY K E Y . ,
,
. ,
,
.
UNIQUE. PRIMARY KEY: ,

.


, . c r e a t e _ d e f i n i t i o n
, PRIMARY KEY, INDEX, UNIQUE, FULLTEXT
FOREIGN KEY. ALTER TABLE
.
t a b l e _ o p t i o n s CREATE TABLE
, DEFAULT CHARACTER SET utf8
ENGINE=InnoDB.
MySQL (http://dev.mysql.com/doc/mysql/en/create-table.htmI).
s e l e c t _ s t a t e n \ e n t
SELECT (. SELECT).
,
. ,
SELECT ,
.
, ,
. c r e a t e _
d e f i n i t i o n s t a b l e _ o p t i o n s CREATE TABLE
,
LIKE.

333

D ELETE
DELETE
{

[LO W _PR IO RITY] [Q U IC K ] [IGNORE]


FROM tbl_name
[WHERE where_clause]
[ORDER BY o rd e r_ b y _ e x p r)
[ L I M I T rows ]

tbl_n am e[, tbl_name ...]


FROM ta b le _ r e fe re n c e s
[WHERE where_clause]

I FROM tbl_nam e [ , tbl_name ...]


USING t a b le _ r e fe re n c e s
[WHERE where_clause] }

(
) WHERE LIMIT,
. WHERE , SELECT (.
SELECT). LIMIT
. ORDER BY ,
, LIMIT
, , ,
.
.
, SELECT
(. SELECT).
t a b l e _ r e f e r e n c e s , SELECT:
. WHERE
. t a b l e _ r e f e r e n c e s
, . ,
, ,
.
LOW_PRIORITY ,
.
QUICK
. IGNORE,
MySQL , .

D E S C R IB E / D E S C
{DESCRIBE

I DESC}

tbl_name [ col_name I w i l d ]

.
,
% _ ( w i l d ) , ( 1_) .
, , ,
, AUTO_lNCREMENT, ,
NULL .

334

MySQL

D R O P DATABASE
DROP DATABASE

[IF

E X IS T S ]

db_name

:
. ,
.
, IF EXISTS.

D R O P IN D E X
DROP INDEX index_name ON tbl_name

ALTER TABLE DROP INDEX, , ALTER TABLE.

D R O P TA B LE
DROP TABLE

[IF

E X IS T S ]

tbl_name [ ,

tbl_name, ...]

.
,
. . ,
.
, IF EXISTS.

E X P L A IN
.
DESCRIBE tbl_nam e SHOW COLUMNS FROM tbl_name.
EX PLAIN

tbl_name

:
EX PLAIN s e le c t_ s ta te m e n t

s e l e c t _ s t a t e m e n t SELECT.
, MySQL
SELECT. ,
.
,
. , ,
MySQL, SELECT
STRAIGHT_J0IN. ,

335

EXPLAIN,
MySQL (http://dev.mysql.com/doc/mysql/en/explain.html).

GRANT
GRANT p r i v _ t y p e [ { c o lu m n _ lis t) ] , ...
ON {tbl_nam e I * I * . * I db_name.*}
TO username [ID E N T IF IE D BY ' passw ord 1] , ...
[W ITH GRANT OPTION]


, username.

IDENTIFIED BY ' p a s s w o r d '.
,
, MySQL
(http://dev.mysql.com/doc/mysql/en/account-management-sql.html).

IN S E R T
IDELAYED] [IGNORE] [IN T O ]
tbl_name
[{col_name, ...) ] VALUES ( e x p r e s s io n , ...) , ...

INSERT

[LOW _PRIO RITY

I SET col_nam e=expression ,


I

[ ( col_name ,

[ON DUPLICATE

col_nam e=expression, ...

...) ] SELECT ... }


KEYUPDATE col_nam e= expression [ ,

...] ]


.
LOW_PRIORITY . ,
.
DELAYED . ,
.
,
, . ,

AUTO_IN.CREMENT.
, last Insert Id PD O
.
IGNO R E . ,
, PRIMARY KEY UNIQUE,
. :
, .

INTO :
.

336

MySQL

, INSERT.
,
. ,
,
.
INSERT
. col_name= value.
INSERT ,
SELECT.
,
.
SELECT, INSERT,
ORDER BY, FROM ,
.
, (,
), . ,
, NOT NULL, NULL. ,
MySQL DONT_USE_DEFAULT_FIELDS,
, .
ON DUPLICATE KEY UPDATE ,
INSERT ,
. UNIQUE
PRIMARY KEY. ,
.
UPDATE:
, .
UPDATE.

L O A D D A TA IN F IL E
LOAD DATA [LOW_PRIORITY I CONCURRENT] [LOCAL] INFILE
' f i l e _ n a m e . t x t ' [REPLACE I IGNORE] INTO TABLE t b l _ n a m e
[FIELDS
[TERMINATED BY 'string']
[[OPTIONALLY] ENCLOSED BY ' c h a r ' ]
[ESCAPED BY ' c h a r ' ] ]
[LINES [STARTING BY ''] [TERMINATED BY 'string']]
[IGNORE n u m b e r LINES]
[(c o l _ n a m e , ...) ]

,
M ySQL- ( LOCAL).
, SELECT INTO OUTFILE.
,
, MySQL
(http://dev.mysql.com/doc/mysql/en/load-data.html).

337

O P T IM IZ E T A B L E
OPTIMIZE TABLE t b l _ n a m e [ , t b l _ n a m e ...]


. MySQL,
,
VARCHAR BLOB. ,
d e f r a g :
.
, ,
, ,
. ,
, RENAME.
, ,
, .

R EN A M E TA B LE
RENAME TABLE t b l _ n a m e TO n e w _ t a b l e _ o a m e [, t b l _ n a m e 2 TO ..., ...]

.
ALTER TABLE tbl_name RENAME ,
,
. MySQL (http://dev.mysql.com/
doc/mysql/en/rename-table.html) , ,
. ,
-
.
CREATE TABLE n e w _ t a b l e (...) ;
RENAME TABLE o l d _ t a b l e TO b a c k u p _ t a b l e , n e w _ t a b l e TO o l d _ t a b l e ;

db_name . tbl_nam e ,
.
, .
,
ALTER DROP , INSERT
. RENAME TABLE, ,
, .

R EP LA C E
REPLACE [LOW_PRIORITY I DELAYED]
{

338

[INTO] t b l _ n a m e

[(c o l _ n a m e , ...) ] VALUES (e x p r e s s i o n , ...) , ...

MySQL

I [(c o l _ n a m e , ...)], SELECT ...


I SET c o l _ n a m e = e x p r e s s i o n , c o l _ n a m e = e x p r e s s i o n , ... }

INSERT. - , PRIMARY
KEY UNIQUE, ,
REPLACE .

R EVO K E
REVOKE p r i v _ t y p e [ { c o l u m n _ l i s t ) ] , ...
ON {tbl_name I * I *.* I d b _ n a m e .*}
FROM u s e r , ...

.
, - ,
.
10 MySQL.

R O LLB A C K
ROLLBACK

START
TRANSACTION, MySQL , ,
.
.

S ELEC T
SELECT [s e l e c t _ o p t i o n s ]
s e l e c t _ e x p r e s s i o n , ...

[INTO {OUTFILE | DUMPFILE} ' f i l e _ n a m e ' e x p o r t _ o p t i o n s ]


[FROM t a b l e _ r e f e r e n c e s
[WHERE w h e r e _ d e f i n i t i o n ]
[GROUP BY {c o l _ n a m e I c o l _ p o s } [ASC I DESC], ...]
[HAVING w h e r e _ d e f i n i t i o n ]
[ORDER BY {c o l _ n a m e I c o l _ p o s } [ASC I DESC] , ...]
[LIMIT [ o f f s e t , ] r o w s ]]

SQL,
. s e l e c t _ o p t i o n s ,
. , ,
.
ALL, DISTINCT DISTINCTROW.

. ALL ,

339

.
DISTINCT DISTINCTROW .
HIGH__PRIORITY . SELECT .
, ,
( SELECT),
. , ,
SELECT HIGH_PRIORITY .
STRAIGHT_JOIN . M ySQL ,
t a b l e _ r e f e r e n c e s . ,
MySQL ,
.
.
SQL_BUFFER_RESULT . MySQL
. ,
,
.
SQL_CACHE . M ySQL ,
,
.
,
, . M ySQ L
, SQL_
CACHE. , .
SQL_NO_CACHE . MySQL
. MySQL- ,
,
. , SQL_NO_CACHE
.
SQL_CALC_FOUND_ROWS . LIMIT.
,
, LIMIT .
SELECT FOUND_ROWS () (. ).

s e l e c t _ e x p r e s s i o n ,
. ,
c o l _ n a m e , t b l _ n a m e .c o l _ n a m e db _nam e. t b l _ n a m e .
c o l _ n a m e . ,
MySQL.
, .
,
, MySQL. ,
1,2010,
.
SELECT DATE_FORMAT(DATE_ADD(CURDATE(), INTERVAL 1 MONTH),

340

'%M %D, % Y ')

MySQL

s e l e c t _ e x p r e s s i o n s (
) .
[AS], .
, -
, WHERE ORDER BY.
SELECT, jokedate AS jd FROM joke ORDER BY jd ASC

MySQL INTO,
, .
CSV,
.
SELECT * INTO OUTFILE '/home/user/myTable.txt'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY
LINES TERMINATED BY '\n'
FROM myTable

, ,
. , SQL-
. ,
,
, ,
.

, OUTFILE DUMPFILE.
BLOB ( SELECT b l o b C o l
INTO DUMPFILE ...). INTO
MySQL (http://dev.mysql.com/doc/mysql/en/select.html).
, ,
LOAD DATA INFILE.
FROM ,
, ,
. t a b l e _ r e f e r e n c e s , , ,
( ) AS,
s e l e c t _ e x p r e s s i o n . ,
. .
w h e r e _ d e f i n i t i o n WHERE ,
,
SELECT. (, id=5),
MySQL ,
AND, OR NOT.
GROUP BY
, (
). , ,
. ,
, COUNT,
AVG (. ),

341

. ,
.
ASC DESC,
.
, . .
WHERE GROUP BY,
, .
,
HAVING. WHERE,

, WHERE , .
GROUP BY HAVING 11.
ORDER BY
, .
, (
) ASC
DESC (
) .
, . .
L I M I T ,
. LIM IT ,
.
, L IM IT , . ,
, k-.
k = 0, k = 1 . .

FROM WHERE ,
. ,
, . MySQL
.
t a b l e _ r e f e r e n c e s , FROM.
ta b le _ re f
ta b le _ re fe re n c e s,

ta b le _ re f

ta b le _ re fe re n c e s

[CROSS] JOIN t a b l e _ r e f

ta b le _ re fe re n c e s

INNER JOIN t a b l e _ r e f j o i n _ c o n d i t i o n

t a b l e _ r e f e r e n c e s STRAIGHT_JOIN t a b l e _ r e f
t a b l e _ r e f e r e n c e s LEFT [OUTER] JOIN t a b l e _ r e f j o i n _ c o n d i t i o n
{ OJ t a b l e _ r e f LEFT OUTER JOIN t a b l e _ r e f ON c o n d _ e x p r }
t a b l e _ r e f e r e n c e s NATURAL

[LEFT [OUTER]] JOIN t a b l e _ r e f

t a b l e _ r e f e r e n c e s RIGHT [OUTER] JOIN t a b l e _ r e f j o i n _ c o n d i t i o n


ta b le

342

r e f e r e n c e s NATURAL

[RIGHT [OUTER]] JOIN t a b l e r e f

MySQL

t a b l e _ r e f .
table_name [[AS] alias] [USE INDEX { k e y _ l i s t ) ]
[IGNORE INDEX { k e y _ l i s t ) ]

j o i n _ c o n d i t i o n .
ON c o n d _ e x p r
USING (c o l u m n _ l i s t )

.
.

. MySQL

, JOIN, CROSS JOIN INNER JOIN (
).
, ,
P H P -. , WHERE SELECT,
, .
,
. .
INNER JOIN j o i n _
c o n d i t i o n . ON (
), ,
, WHERE ,
.
j o i n _ c o n d i t i o n y
USING (c o l u m n _ l i s t ), ,
.
SELECT * FROM tl INNER JOIN t2 USING (tid)

.
SELECT * FROM tl INNER JOIN t2 ON tl.tid = t2.tid

STRAIGHT_J0IN , ,
,
( , ). , MySQL ,
, ,
, STRAIGHT_JOIN.
MySQL
LEFT/RIGHT [OUTER] JOIN. OUTER
. ( LEFT )
, ,
j o i n _ c o n d i t i o n , .
, , NULL.

343

{ J ... } .
,
ODBC (Open Database Connectivity).
, ,
,
. ,
LEFT JOIN.

.
,

. , j authorid,
author,
authorid,
( ,
).
SELECT * FROM joke NATURAL JOIN author

UNION
UNION
SELECT, .
, .
, .
SELECT ...
UNION [ALL | DISTINCT]
SELECT ...
[UNION [ALL | DISTINCT]
SELECT ...] ...

UNION ,
.
DISTINCT, .
, ALL.

SET
SET o p t i o n = value, ...

,
.
,
, SET autocommi t = 0. ,
, START TRANSACTION,
COMMIT ROLLBACK. autocommit

344

MySQL

, ,
INSERT, UPDATE DELETE ,
COMMIT.
, SET,
MySQL (http://dev.mysql.com/doc/
mysql/en/set-option.html).

SHOW

MySQL, .
LIKE w i l d , w i l d
,
(% _ ).
.
SHOW DATABASES [LIKE w i l d ] .
M ySQL-.

SHOW [OPEN] TABLES [FROM db_name] [LIKE w i l d ] .


( OPEN)
.
SHOW [FULL] COLUMNS FROM tbl_name [FROM db_name]
[LIKE
w i l d ] . FULL ,
, DESCRIBE (. D ESC R IB E/D E SC ).
FULL
. SHOW FIELDS SHOW COLUMNS .
SHOW INDEX FROM t b l _ n a m e [FROM db_name] .
, .
, ,
MySQL (http://dev.mysql.com/doc/en/show-index.html). SHOW
KEYS SHOW INDEX .

SHOW TABLE STATUS [FROM db_name] [LIKE w i l d ] .


.
SHOW STATUS [LIKE w i l d ] . .
MySQL
(http://dev.mysql.com/doc/en/show-status.html).
SHOW VARIABLES [LIKE w i l d ] .
MySQL.
MySQL (http://dev.mysql.com/doc/en/show-variables.html).
SHOW [FULL] PROCESSLIST . ,
M ySQL-, , .
process,
. FULL
(
100 ).

345

SHOW GRANTS FOR u s e r . GRANT,


.

SHOW CREATE TABLE ta b le _ n a m e . CREATE TABLE,


.

S T A R T T R A N S A C T IO N
START TRANSACTION

(
), MySQL
, , (COMMIT)
(ROLLBACK) .

TRUNCATE
TRUNCATE [TABLE]

tb l_ n a m e

, DELETE
WHERE, . TRUNCATE
, ,
.
DROP TABLE, CREATE TABLE.
**,- ,

'

/-

UPDATE
UPDATE [LOW_PRIORITY] [IGNORE] t b l _ n a m e
SET c o l _ n a m e = e x p r [, ...]
[WHERE w h e r e _ d e f i n i t i o n ]
[ORDER BY ...]
[LIMIT #]

,
. , , ,
TIMESTAMP (. ). WHERE
w h e r e _ d e f i n i t i o n ,
. LIMIT
, .

WHERE LIMIT________________________

WHERE LIMIT ,
.

ORDER BY .
LIMIT:
.

346

MySQL

, ,
, ,
PRIMARY KEY UNIQUE. , IGNORE
.
LOW_PRIORITY MySQL ,
.
DELETE (. DELETE), UPDATE
, .
UPDATE [LOW_PRIORITY] [IGNORE] t b l _ n a m e [, t b l _ n a m e ...]
SET c o l _ n a m e = e x p r [, ...]
[WHERE w h e r e _ d e f i n i t i o n ]

USE
USE d b _ n a m e

,
MySQL .
db_name. tbl_name.


M ySQ L

MySQL ,
SQL-,
.
, MySQL 5.5.22
.
SQ L -
M ySQ L ( http://dev.mysql.com/doc/mysql/en/
functions.html).



IF N U L L ( exprl, 2)

e x p r l , NULL.
2 .
N U L L IF ( exprl, expr2)

e x p r l , 2 .
NULL.
I F ( exprl, expr2 , )

e x p r l , NULL 0,
2 , .
CASE value WHEN [compare-value 1] THEN resultl [WHEN ...] [ELSE
else-result] END

r e s u l t l , v a lu e = c o m p a r e - v a l u e l (
). e l s e r e s u l t NULL, .
CASE WHEN

result ] END

348

[conditionl]

THEN resultl

[WHEN ...]

[ELSE

else-

MySQL

c o n d i t i o n l , r e s u l t 1 (
).
e l s e - r e s u l t NULL, .


ABS ( )
v

() .
S IG N ( )

- 1 ,0 1 ,
(, ).
MOD( exprl, 2 )

exprl % expr2
e x p r l 2.
FLOOR( )

,
, .
C E IL IN G ( )
C E IL ()

,
, .
ROUND ( )

, .
,
. ,
ROUND , .
ROUND( ,

,
, . ,
/ , 2.
, .
( )

,
.

349

LOG( expr)

In( e x p r ) loge ( e x p r )
expr.
LOG( ,

expr)

e x p r .
_________________ ______________

L0G(8, expr ) = LOG (expr) / LOG(B)


LOG1 0 (expr)

e xp r.
POW( exprl, expr2)
POWER( exprl, expr2)

e x p r l , e x p r 2.
SQRT( expr)

ex pr.
PI

.
COS( expr)

e x p r , COS (PI () )=-1.


S IN ( expr)

e x p r , SIN (PI () )=0.


TAN( expr)

e x p r , TAN (PI () )= 0.
ACOS (expr)

(cos-1, ) e x p r
, ACOS (-1) =1 ().
AS IN ( expr)

(sin-1, ) e x p r ,
ASIN (0) =1 ().

350

MySQL

ATAN ( expr)

(tan -1, ) e x p r
, ATAN (0) =1 ().
ATAN ( ,

ATAN2 ( , )

,
(, ), AT AN (1,0)= PI 0/2.
( e x p r )

expr, ( PI () /2 ) = 0.
RAND()
RAND( e x p r )

0 1,0.
e x p r ,
, .
LEAST ( e x p r l , expr2 , ...)

.
GREATEST ( exprl , expr2 , ...)

.
DEGREES( expr)

.
RADIANS( expr)

.
TRUNCATE( expr, )

e x p r
, , .
B IN ( expr)

e x p r .
CONV(expr, 10, 2).
( expr)

e x p r .
C O N V (e x p r , 10, 8).

351

HEX ( )

.
CONV ( , 10, 16).
CONV ( , froiajbase, to_Jbase)

fro m _ b a s e to _base .
NULL, NULL.


A S C II ( s t r )

A SC II- s t r ; 0,
, NULL, NULL.
ORD(str)

ASCII- s tr, ,
.
CHAR {, ...)

, ASCII-, .
CONCAT ( strl, str2, ...)

,
, . -
NULL, NULL.
CONCAT_WS (separator, strl , str2, ...)

CONCAT (W S -
with separator).
.
LENGTH ( str)
OCTET_LENGTH( str)
CHAR_LENGTH( s t r )
CHARACTER_LENGTH( str)

str . C H A R _ L E N G T H
CHARACTER_LENGTH .
BIT_LENGTH( s t r )

s t r , B I T _ L E N G T H ( s t r ) =
=8*LENGTH(str).

352

MySQL

LOCATE ( s u b s t r ,

s tr)

P O S IT IO N ( s u b s t r IN

s tr)

s u b s t r s t r (1
, 2 . .). su b s t r
s t r , 0.
LOCATE ( substr, str, pos)

LOCATE ( s u b s t r , s t r ) , ,
pos.
IN S TR ( str, substr)

LOCATE ( s u b s t r , s t r )
.
LPAD( str, len, padstr)

s t r 1.
pa d s t r s t r . , LPAD ( '! 1, 15 ',
' . ' ) = 1 . . . . ! '.

RPAD (str, len, padstr)

s t r l e n .
p a d s t r s t r . ,
R P A D (' ! , 15', '.') = '!____ \
L E F T ( Str, len)

s t r , len.
, 1, s t r
.
R IG H T ( str, len)

s t r , le n .
, 1, s t r
.
SUBSTRING( str, pos, len)
SUBSTRING (Str FROM pos FOR len)
M I D ( s t r , pos, len)

s t r , ,
l e n , p o s, 1 . SUBSTRING
ANSI.
S U B S T R IN G (s tr, pos)
S U B S T R IN G (S tr FROM p o s )

353

s t r , p o s , 1
.
S U BSTRING _IN DEX( s t r ,

delim, count)

MySQL coun t d e l im s t r
. c o u n t ,
,
. coun t ,
, s t r .
LTR IM ( s t r )

s t r , .
R TR IM ( str)

s t r , .
T R I M ( [ [BOTH

| LEADING

I T R A IL IN G ]

[ remstr ] FROM]

s tr)

s t r ( )
re m s tr.
( ) LEADING, TRAILING BOTH .
S O U N D E X (S tr)

, , s t r .
, , .
:
SOUNDEX("tire") = ""
SOUNDEX("tyre") = "600"
SOUNDEX("terror") = "T600"
SOUNDEX("tyrannosaur") = "T6526"

SPACE(num)

, .
.
REPLACE (str, from^str,

to^str)

s t r , f r o m _ s t r
t o _ s t r .
REPEAT( str, count)

s t r , ,

count. co u n t 0, .
NULL, NULL.

354

MySQL

REVERSE (Str)

s t r .
INSERT ( str, pos, len, newstr)

s t r l e n , p o s ,
1 .
n e w s t r . 1 0, n e w s t r .
E L T (N ,

strl, str2, str3, ...)

N- ( s t r l , N = 1; s t r 2, N = 2, . .)
NULL, .
F IE L D ( str, strl, str2, str3, ...)

s t r (1, s t r
s t r l ; 2, s t r s t r 2, . .).
F IN D _ IN _ S E T ( str, strlist)

s t r l i s t ' s t r i n g l , s t r i n g 2 ,
string3
s t r , ,
0, .
, s t r SET (. ).
MAKE_SET ( ts, strl, str2, ...)

1s t r i n g l , s t r i n g 2 , s t r i n g 3

( s t r l , s t r 2 . .), ,
ts . , b i t s 10 (1010
), 2 4, MAKE_SET ' s t r 2 , s t 4 '.
EXPORT_SET (bits,

on_str, off__str[,

separator[, number_of_

bits ] ] )
, ( )
b i t s .
o n _ s t r , o f f _ s t r . ,
s e p a r a t o r .
64 , ,
n u m b e r _ o f _ b i t s .
:
EXPORT_SET(10,

'Y', 'N',

',', 6) = 'N,Y,N,Y,N,N'

LCASE (str)
LOWER (str)

s t r , .

355

UCASE( s t r )
U P P E R (s tr )

s tr, .
LO AD_FILE ( f i l e n a m e )

, f i l e n a m e ,
, M ySQL.
.
Q U O T E (s tr)

str
. s t r
NULL, NULL ( ).


DAYOFW EEK(date)

da t e
ODBC: 1 , 2 , 3 ... 7 .
I

W EEK D A Y(date)

d a t e : 0
, 1 , 2 ... 6 .
DAYOFMONTH( d a t e )

d a t e 1 31.
DAYOFYEAR( d a t e )

d a t e 1 366
( ).
M O N T H (d a te )

d a te 1 ()
12 ().
DAYNAME( d a t e )

da te. , ' '.


MONTHNAME(date)

date. , ' '.

356

MySQL

QUARTER(date)

d a t e . , Q U A R T E R
04- 1 2 ' ) = 2.

( ' 2005 -

WEEK( date[, mode])

d a t e
0 53, 1 .
.
,
. .1.
.1.

0 53

0 53

1 53

1 53

0 53

0 53

1 53

1 53

YEAR ( d a t e )

d a t e 1000 9999.
YEARWEEK( d a t e )
YEARWEEK(d a t e ,

first)

d a t e ' YYYYWW'.
,
, .
:
YEARWEEK("2006-12-31")=200701

HOUR ( t i m e )

tim e 0 23.
MINUTE ( t i m e )

tim e 0 59.

357

SECOND (time)

tim e 0 59.
PERIOD_ADD( period, num_months)

p e r i o d num_months,
' Y Y M M ' ' YYYYMM ', 1YYYYMM '.
P E R IO D _D IFF (periodl, period2)

p e r i o d l p e r i o d 2 ,
' Y Y M M ' ' YYYYMM'.
D A T E _ A D D (d a te ,

INTERVAL expr type)

DATE_SUB( date,

INTERVAL expr type)

ADDDATE( date,

INTERVAL expr type)

SUBDATE (date, INTERVAL expr type)

d a te
tim e ( DATE DATETIME). DATE_ADD
ADDDATE, DATE_SUB SUBDATE . e x p r
, .
. e x p r
t y p e (. .2).
d a t e e x p r ,
DATE. DATETIME.
.
,
, :
ADDDATE(CURDATE(), INTERVAL 6 MONTH)
DATE_ADD(CURDATE() , INTERVAL '0-6' YEAR_MONTH)

, .
ADDDATE(N O W (), INTERVAL 1 DAY)
SUBDATE(N O W (), INTERVAL -1 DAY)
DATE_ADD(N O W (), INTERVAL '24:0:0' HOUR_SECOND)
DATE_ADD(NOW(), INTERVAL '1 0:0' DAY_MINUTE)

.2.

SECOND

MINUTE

HOUR

358

MySQL

DAY

MONTH

YEAR

MINUTE_SECOND

' :'

HOUR_MINUTE

' : '

DAY_HOUR

' 1

YEAR_MONTH

'-'

HOUR_S ECOND

' : :'

DAY_MINUTE

' : '

DAY_SECOND

' ::'

T O _ D A Y S (d a te )

, .
, 0_DAYS (d a t e 1) - _
DAYS ( d a t e 2) = da t e l da te2.
FROM_DAYS( days)

, .
, TO_DAYS.
DATE_FORMAT( d a t e , format)

d a te
forma t. -, ,
. ..
.. - D A T E _F O R M A T (2004-01-01 01:00:00)

%w

%D

%Y

(, 4 )

2004

(, 2 )

03

%d

01

%m

01

%j
%

001

(24- , 00-23)

01

1st

359

(24- , 00-23)

%h

(12- , 01-12)

01

%1

(12- , 01-12)

01

%1

(12- , 1-12)

%1

(12- , hh:mm:ss / )

(24- , hh:mm:ss)

%S

00

%s

00

AM

%w

, ( 0 )

%U

(00-53, )

00

%u

(00-53, )

01

,
(, 4 , %V)

%V

(01-53, (%))

%,
( %v)

%v

(01-53, (%))

01

%%

00
01:00:00 AM
01:00:00

AM

2003
53
2004

TIME_FORMAT (time, format)

DATE_FORMAT. ,

f o r m a t , ,
.
CURDATE( )
CURRENT_DATE

SQL 1YYYY-MM-DD ' (


) YYYYMMDD ( ).
C U R TIM E( )
CURRENT_TIME
CURRENT_TIM E( )

SQL ':: SS ' (


) HHMMSS ( ).

360

MySQL

NOW ( )
SYSDATEO
CURRENT_TIMESTAMP
CURRENT_TIMESTAMP( )
LOCALTIME
LO CA LTIM E( )
LOCALTIMESTAMP
LOCALTIMESTAMP( )

SQL ' YYYY-MM-DD


: : SS ' ( /) YYYYMMDDHHMMSS (
).
U N IX _TIM E S TA M P ( )
U N I _ IMESTAMP( d a t e )

/ /
, 1970-01-01 00:00:00 GMT.
FR O M _U N IXTIM E( _ t i m e s t a m p )

UNIX_TIMESTAMP, ,
1970-01-01 00:00:00 GMT, ' YYYY-MM-DD HH:MM:SS ' (
/ ) YYYYMMDDHHMMSS (
). .
FR O M _U N IX TIM E (u nx__tmestamp, f o r m a t )

UNIX- f o r m a t ,
-, . ..
SEC_TO_TIME ( s e c o n d s )

1 : : SS ' (
) HHMMSS ( ).
TIM E_TO_SEC ( t i m e )

'HH:MM:SS' .


DATABASE( )

.
, .
1

361

USER ()
SYSTEMJCJSER ()
SESSION_USER()

MySQL ,
' k e v in @ l o c a l h o s t 1. SUBSTRING_INDEX
.
SUBSTRING_INDEX(USER(), "@ ", 1) = 'kevin'

CURRENT_USER()

MySQL
' u s e r @ h o s t ',
. ,
USER. ,
, CURRENT_USER
, 1@%. my c o m p a n y . c o m '.
PASSWORD(str)

.
( ) 16 .
- .

.
PASSWORD ,
UNIX. ENCRYPT.
ENCRYPT(strl, salt ] )

s t r UNIX
c r y p t (). s a l t
, ,
. , ,
, s a l t
.
c r y p t ()
.
, crypt () , NULL.
ENCODE(str, pass^str)

s t r , p a s s _
s t r . DECODE.
DECODE ( crypt^str, pass_str)

c r y p t _ s t r ,
p a s s _ s t r . ,
, ENCODE.

362

MySQL

MD5( string)

s t r i n g MD5.
32- .

. MD5 (NOW () ) , , ,
.
LA S T_IN S E R T_ID ()

,
AUTO_INSERT.
FOUND_ROWS()

LIMIT SELECT
, , .
SELECT: SQL_CALC_
FOUND_ROWS (. ), FOUND_ROWS.
,
LIMIT,
.
FORMAT( expr , num)

e x p r , ,
,
. ,
.
VERSION( )

M ySQL-, ' 5 . 1 . 3 4 ' .


CONNECTION_ID()

.
GET_LOCK( str,

timeout)


, ,
.
s t r . ,
t i m e o u t ,
.

RELEASE_LOCK , GET_LOCK.
, GET_LOCK 1, t i m e o u t 0.
- NULL.

363

GET_LOCK MySQL
.
:
SELECT GET_LOCK("mylock", 10)

RELEASE_LOCK( s t r )

, GET_LOCK.
1, , 0,
, NULL, .
IS_FR EE_LO C K ( s t r )

, .
1, , 0, - , NULL,
.
BENCHMARK( c o u n t ,

expr)

e x p r
, coun t. MySQL
.
IN E T_N TO A ( e x p r )

IP -, e x p r.
INET_ATON.
IN E T_A TO N ( e x p r )

IP - e x p r .
:
INET_ATON(64.39.28.1') = 64 * 2553 + 39 * 2552 + 28 * 255 + 1
= 1063751116

,
G R O U P BY
, GROUP
BY, . ,
.
GROUP BY,
,
.
, , ,
,
.

364

MySQL

COUNT( )

, NULL . COUNT (*)


, , NULL .
COUNT (D IS T IN C T e x p r l , ...] )

,
NULL ( , ).
AVG ( )

,
.
M IN ( )
( )


.
SUM( )

.
%

STD( )
STDDEV( )


.
B IT_O R ( )
B IT_A N D ( )

/
.


M yS Q L

MySQL
. ,
MySQL 5.5.22 .

,
.
. ,
.
,
,
. 1 255.
, INT, ,
: ,
, ZEROFILL (
).
, , ,
.
D ,
.
30 , .
, D -2. ,
.
.
, ,
.
ZEROFILL. .
.
UNSIGNED.
UNSIGNED .
. ,
. ,
, .
BINARY. MySQL,
, ,
BINARY .

366

MySQL


MySQL (http://dev.mysql.com/doc/mysql/en/
data-types.html).


T IN Y IN T [ () ]
:

: UNSIGNED, ZEROFILL.
: - 1 2 8 127 ( 0 255, UNSIGNED).
:

1 (8 ).

SMALLINT [ () ]
:

: UNSIGNED, ZEROFILL.
:

- 3 2 768 32 767 ( 0 65 535, UNSIGNED).

2 (16 ).

M EDIUM INT [ ( ) ]
:

: UNSIGNED, ZEROFILL.
:

- 8 588 608 8 388 607 ( 0 16 777 215,

UNSIGNED).
:

3 (24 ).

IN T [ () ]
:

: UNSIGNED, ZEROFILL.
:

- 2 147 483 648 2 147 483 647 ( 0 4 294 967 295,

UNSIGNED).
:

4 (32 ).

: INTEGER [ () ].

B IG IN T [ (Af) ]
:

: UNSIGNED, ZEROFILL.
: - 9 223 372 036 854 775 808 9 223 372 036 854 775 807
( 0 18 446 744 073 709 551 615, UNSIGNED).
:

8 (64 ).

367

. M ySQL
BIGINT. , BIGINT UNSIGNED,
9 223 372 036 854 775 807 (63 ),
, AND, OR NOT.

, - ,
.
FLOAT [ (,

D) ]

FLOAT ( p r e c i s i o n )

: .
: ZEROFILL.
: 0 1,175494351-38 +3,402823466+38.
: 4 (32 ).
. p r e c i s i o n
24 , DOUBLE.
DOUBLE [ ( , D) ] , DOUBLE ( p r e c i s i o n )

: .
: ZEROFILL.
:
1,7976931348623157+308.

2,2250738585072014-308

: 8 (64 ).
. p r e c i s i o n
25 , FLOAT (. ).
p r e c i s i o n 53.
: DOUBLE PRECISION [ (, D) ] REAL [ (, D) ].
DECIMAL [ ( [ , D] ) ]

: .
: ZEROFILL.
: DOUBLE, D
(. ).
. .
X Y ,
(X + ) 4 - 10 .
. D , ,
,
. , 10.
: NUMERIC ( [[ ,D] ] ) .

368

MySQL

1()

. ,
1 64. , ,
0 1.
: .
: + 2 (8 + 16 ).
.
(true false). BIT : b ' ddd...1,
d 1 (true) 0 (false) . ,
true: b ' 1 1 1 1 1 1 1 1 '.


CHAR ()

: .
: BINARY.
: (8 ).
. CHAR
, . ,
, ,
, .
.
CHAR ,
, VARCHAR.
.
0 255. CHAR (0)
1 NULL ( ' ' ).
: CHARACTER ( ) .
VARCHAR ( )

: .
: BINARY.
: .
: 1
(2 , > 255)
. VARCHAR ,
,
255 MySQL, 5.0.3.
, MySQL
65 535 . ,
, ,

369

. ,
, TEXT.
, ,
. MySQL, 5.0.3,
,
. 5.0.3,
, .
: CHARACTER VARYING ().
BINARY ()

: .
: .
: (8 ).
. CHAR , MySQL
, , .
VARBINARY ()

: .
: .
: 1
.
. VARCHAR , MySQL
, , .
TINYBLOB
TIN Y T E X T

: .
: 255 .
: 1

. VARCHAR (255) BINARY VARCHAR (255)
. ,
. TINYBLOB TINYTEXT
, ,
.
BLOB
TEXT

: .
: 65 535 (65 ).

370

MySQL

: 2
.
. BLOB TEXT
, , .
MEDIUMBLOB
MEDIUMTEXT

: .
: 16 777,215 (16,8 ).
: 3
.
. MEDIUMBLOB MEDIUMTEXT
, ,
.
LONGBLOB
LONGTEXT

: .
: 4 294 967 295 (4,3 ).
: 4
.
. LONGBLOB LONGTEXT
, ,
.
ENUM( value1, value2 ,

...)

: ,
.
: 65 535 .
: 1 255 1 (8 ); 256
65 535 2 (16 ).
. ,
: 1 , 2
. . ,
( ' ') .
, NOT NULL,
, .
S ET( value1, value2 ,

...)

: , (
, ).

371

: 64 .
: 1 8 1 (8 ); 9
16 2 (16 ); 17 24 3 (24 ); 25
32 4 (32 ); 33 64 8 (64 ).
. ,

. ,
. 01010101
85.
, , , .
, 11, , ,7 1= 85.
LIKE
FIND_IN_SET.


DATE

: .
: ' 1000-01-011 ' 9999-12-31 ', ' 0000-00-00 '.
: 3 (24 ).
TIM E

: .
: ' -83 8 : 59 : 59 ' '838:59:59'.
: 3 (24 ).
DATETIME

: .
: ' 1000-01-01 00 : 00 : 00 ' ' 9999-12-31 23:59:59'.
: 8 (64 ).
YEAR

: .
: 1901 2155, 0000.
: 1 (8 ).
. ( 1901 2155
0000), ( ' 1 9 0 1 ' ' 2 1 5 5 ' ' 0000 ' ),
( 70 99 1970 1999, 1 69
2001 2069 0 ) ( ' 70 '
' 9 9 ' 1970 1999 ' 0 0 ' ' 6 9 ' 2000 2069).

372

MySQL

2000- ,
. 0.
TIMESTAMP [ ( ) ]

: (/) YYYYMMDDHHMMSS.
: 19700101000000 2037
( ).
: 4 (32 ).
. ( INSERT
UPDATE ),
TIMESTAMP, , ,
/. /
. ,
NULL
. , ,
, .
14,12,10,8,6,4 2,
YYYYMMDDHHMMSS, YYMMDDHHMMSS, YYMMDDHHMM, YYYYMMDD, YYMMDD,
YYMM YY. 1 13
. 14 14.

+ ( ):

_ ( ) 203

198

| ( ) 198

61

II ( )
77

- ( ) 61
( ) 53

< ( ) 79

( ) 53

< = ( )79

$ ( ):

> ( ) 79

61

> = ( ) 79

198

-> () 9 4 -9 5

% ( ) 55

= () 61

&& ( ) 77

== ( ) 76

* ():

!= ( ) 79

198
61
** ( ) 203

? ( ):
198
107

. ():

198
62,99

ABS( ) 349

.= 82

A CO S( ) 350

; ( ) 59

A D D A TE( ) 358

/ ():

A LTER TABLE 124, 328-331

200

A LTER TABLE A DD U N IQ U E 226

61

ANALIZE TABLE 331

/ / ( ) 62

and, 77

\ ( ) 5 3 ,1 0 9 ,1 9 9

Apache 22

\ \ ( ) 53, 200

( ) ( ) 198

Linux 323-3 2 5

[ ] ( ) 199, 212

- Mac OS X 3 0 -3 4 ,3 1 7 -3 1 9

( ) 198

- W indow s 2 4 -2 9 ,3 0 7 -3 0 9

374

A SC II( ) 352

CO NV ( ) 352

A S IN ()3 5 0

copy 282

A T A N () 351

C O S ( ) 350

A T A N 2 () 351

C O T ( ) 351

A V G () 365

C O U N T ( ) 365
CREA TE DATABASE 331

CREA TE IN DEX 3 31-332

BEG IN 331

CREA TE TABLE 332-3 3 3

BENCHM ARK^ ) 364

C U R D A T E () 111,360

BIG IN T 367

C U R R EN T_D A T E( ) 360

BINARY( ) 370

C U R R E N T _T IM E ( ) 360

Binary large objects .

C U R R E N T _T IM E ST A M P( ) 361
C U R R E N T _U SE R ( ) 362

BIT_A N D ( ) 365

C U R T IM E ( ) 360

B IT _ L E N G T H () 352
B IT _O R ( ) 365

BLOB .
370-371

D A TE_A D D ( ) 358
D A T E_FO R M A T( ) 359

break, 277

D A TE_SU B ( ) 358

CASE 348-349
C EIL ( ) 349
C EIL IN G ( ) 349
CH A R 369
C H A R () 352
C H A R _L EN G T H ( ) 352
C H A R A C TE R _LEN G TH ( ) 352
CM S .
C O M M IT 331
CO N CA T( ) 352
C O N C A T _ W S () 352
C O N N E C T IO N _ID ( ) 363
C ontent M anagem ent System .

DAYNAM E( ) 356
D A Y O FM O N T H ( ) 356
D A Y O FW EEK ( ) 356
DAYOFYEAR( ) 356
D EC IM A L 368
D E C O D E ( ) 362
D E G R E E S () 351
D ELETE 5 6 -5 7 ,3 3 4
D ESC R IB E 52,124
D E S C R IB E /D E S C 334
D IST IN C T 125
D O U B LE 368
D R O P DATABASE 335
D R O P INDEX 335
D R O P TABLE 335

375

ELT( ) 355

ID E .

E N C O D E () 362

if else, 7 5 -7 7

EN CRY PT( ) 362

IF ( ) 348

ENUM 371

if, 7 3 -7 4

E X P ( ) 349

IFN U LL( ) 348

EXPLAIN 335-3 3 6

IIS . In tern et Inform ation Services

E X P O R T _S E T ( ) 355

include 143
include_once 144

IN ET_A TO N ( ) 364

F I E L D () 355

IN ET_N TO A ( ) 364

file_exists 282

InnoD B 51

file_get_contents 282

IN SER T 5 2 -5 3 ,3 3 6 -3 3 7

file_put_contents 282

IN S T R () 353

F IN D _IN _SE T ( ) 355

INT 367

FLO A T 368

In tern et Inform ation Services 22, 27 -2 8 , 145,


30 6 -3 0 8

F L O O R ( ) 349
for, 7 9 -8 0

IS JF R E E _ L O C K ( ) 364

foreach, 10 5 -107,116

FO R M A T( ) 363
F O U N D _R O W S ( ) 363

kill 260

FRO M _D A Y S( ) 359
L

FR O M _U N IX T IM E ( ) 361

LAST INS E R T_I D ( ) 363


G

LCASE( ) 355

G E T _L O C K ( ) 363-3 6 4

LEAST( ) 351

GRANT 336

LE FT JO IN 277-279, 344

G R EA TEST( ) 351

LE FT ( ) 353

G R O U P BY, M ySQ L 3 64-3 6 5

LE N G TH ( ) 352
LOAD DATA IN FILE 337

LO A D _FILE ( ) 356

H EX ( ) 352

localhost 28,32

H O U R ( ) 357

LO C A LTIM E( ) 361

htm lspecialchars 67

LO C A LTIM ESTA M P( ) 361

376

LO CA TE( ) 353

2 59-260

LO G ( ) 350

253-257

LO G 10( ) 350

mysqldump 2 54-255

LO N GBLOB 291,371
LO N G TEX T 371

phpM yAdm in 253-254



255-257

L O W E R () 355

L P A D () 353

Linux 320-3 2 3

LT R IM ( ) 354

- M a c OS X 3 1 3 -3 1 6
M
M A K E_SET( ) 355

W indow s 3 0 5 -3 0 6
8 8-91
mysqlbinlog 257

M AM P 30
3 2 -3 4

mysqldump 257

3 0 -3 1
N

M A M P P R O 31
M arkdown, 201

N O W ( ) 361

M AX( ) 365

N U L LIF( ) 348

md5 226-227

M D 5( ) 227,365
M E D IU M B L O B 371

O C T ( ) 351

M E D IU M IN T 367

O C T E T _ L E N G T H () 352

M E D IU M T E X T 371

O P T IM IZ E TABLE 338

M I D ( ) 353

or, 77

M IN( ) 365

O R D ( ) 352

M IN U T E ( ) 357

O R D E R BY 269,346

M O D ( ) 349
M O N TH ( ) 356

M O N TH N A M E( ) 356

PA SSW O R D ( ) 362

M ySQ L 22,41

P D O cm. P H P D ata Objects

2 52-267

PD O E xception 93

260-261

P E R IO D _A D D ( ) 358

3 4 -3 6

P E R IO D _ D IF F ( ) 358

2 9 -3 0
9 1 -1 0 0

P H P 2 2 ,4 1 ,5 8 -5 9
5 9-61

377

62

R PA D ( ) 353

216-225

R TR IM ( ) 354

22
S

:
Linux 3 23-327

S E C _T O _T IM E ( ) 361

- M a c OS X 3 16-319

SEC O N D ( ) 358

-W in d o w s 306-3 1 3

SELEC T 3 39-344

P H P D ata O bjects 9 1 ,9 3 -1 0 0

Server side includes, 138

phpM yAdm in 42

S E S S IO N _ U S E R () 362

4 4 -4 5

SET 3 44-3 4 5

4 2 -4 3

setcookie 211-214, 217

P I( ) 350

S H O W 3 4 5 -3 4 6

P O S IT IO N ( ) 353

S IG N () 349

P O W ( ) 350

S I N ( ) 350

P O W E R () 350

skip-grant-tables 261
SM ALLINT 367
Q

S O U N D E X ( ) 354

Q U A R TE R ( ) 357

SPA C E( ) 354

Q U O T E () 356

SSI cm. Server side includes,


R

R A D IA N S () 351
R A N D () 351

SQL .

48
SQ L-:

RELEA SE_LO C K ( ) 364

4 4 -4 5

RENAM E TABLE 338

100-102

R EPEA T( ) 354

110

REPLA CE 338-339

268-280

require 143

SQ L-, 109

re q u ire o n c e 144

SQ R T( ) 350

R E V E R S E () 355

START TRA N SA CTIO N 346

REV O K E 339

S T D ( ) 365

R IG H T ( ) 353

S T D D E V () 365

ROLLBACK 339

str_replace 206

R O U N D ( ) 349

S U B D A T E () 358

378

SU B STR IN G ( ) 353

SU B ST R IN G _IN D EX ( ) 354

VARBINARY 370

SU M ( ) 365

VARCH A R 369

SYSDATE( ) 361

V ER SIO N ( ) 363

SY ST EM _U SER ( ) 362
W
T

W E E K ( ) 357

TAN( ) 350

W EEK D A Y ( ) 356

TE X T 370-371

while, 7 7 -7 9

T extE dit, 3 5 -3 6

- 38
T IM E _F O R M A T ( ) 360

X A M PP 23

T IM E _T O _S E C ( ) 361

2 6 -2 9

TIM E ST A M P 373

2 4 -2 6

TINYBLOB 291,370
TIN Y IN T 367

TIN Y TEX T 370

YEAR 372

T O _ D A Y S () 359

YEAR ( ) 357

TRU N CA TE 346

Y EA RW EEK ( ) 357

try catch, 9 2 -9 3

A
U

U CASE( ) 356

125

U N IO N 344

125

U N IX _T IM E ST A M P( ) 361
unlink 282

53
71

U PD A TE 56, 346-3 4 7
upload_max_filesize 2 87-288
U P P E R ( ) 356

U SE R ( ) 362

49

userH asRole 230, 233, 237

45

userlsLoggedln 230, 232-233

107-115

U TF-8 68, 96

2 25-228

379

48
4 6 -4 7

42

115-121

265-267
162

255-257

62

, :
- 38

225-2 5 0
2 11-216

- 2 2 -2 3

211-212
213

3 8 -3 9 ,1 4 5

Linux 36
- - Mac OS X 3 0 -3 6

, 269-271

W indow s 2 3 -3 0

- 3 6 -3 7
.
. Server side includes,

109

6 2 -6 3
63
105
95

289
.

3 2 -3 3

281-302

149

51

149
149

216
:

3 42-344
290

261-265

.
-

63

276-2 7 9

38

62

6 1 -6 2

9 2 ,9 8 -9 9

62, 99,172

380

201-204

134-135
132

2 06-208
103

132

132

156-193

366

198

6 1 -6 2

149

198

150-151

227

6 4 -7 0

162

7 0 -7 3

267
41

:
H T M L - 137-139

272-274

- 139-143

290-291

372-3 7 3

- 9 3 -9 5

369-3 7 2

137-155

3 6 7 -3 6 9

132-134

281-285

94

4 0 ,4 7 -4 8

110

. M ySQL

145

.
125-128

;
274-2 7 6

41
128-132


HAV IN G 2 79-280

5 2 -5 3

268-2 6 9

5 4 -5 6

195-200

272-274

204-20 6

56

205

4 9 -5 2

381

5 6 -5 7
53

138
:

78

271-272


151-155

60
60

:
73

364

199

356-361
348-349

G R O U P BY
3 64-3 6 5

:
3 49-352
, 3 02-303
146-148

2 89-296

147

2 86-289

3 5 2 -3 5 6

293-296

, 285
137-144
144-146
291-293

6 4 -7 3


53,199

41
63

MySQL

( )
.
.
.


123308, , . , . 1. . 8 (495) 411 -68-86,8 (495) 956-39-21.
Home : www.eksmo.ru E-mail: infoQeksmo.ru
9|: , 123308, , , , 1 .
. 8 (495) 411 -68-86, 8 (495) 956-39-21
: www.eksmo.ru E-mail: info@eksmo.ru.
rid:
1
-
1 - , ., ., 3, , 1.
.: 8 (727) 2 51 59 89,90,91,92, : 8 (727) 251 58 12 . 107; E-mail: RDC-Almaty@eksmo.kz
HiMHiH MepdMi .
: www.eksmo.ru/certiflcation


: http://eksmo.ru/certification/
91 :

10.10.2013. 701001/ 1*
. . . . 31,11.
2000 . 8413.

,

432980, . , . , 14

ISBN 978-5-699-67363-6

9785699673636
7 8 5 6 9 9 672 62 i">