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

-

-
2006

681.3.06
32.973.26-018.2
85

. .
85

MySQL. . .: -, 2006.
208 .: .
ISBN 5-94157-658-7
MySQL -.
:
PHP, . , . , , ,
, - web-.
-,
, , MySQL , GNU/GPL.

681.3.06
32.973.26-018.2

:

.
.

02429 24.07.00. 22.03.06.


70 1001/16. . . . . 16,77.
3000 .
"-", 194354, -, . , 5.
-
77.99.02.953..006421.11.04 11.11.2004 .
.

" ""
199034, -, 9 , 12

ISBN 5-94157-658-7

. ., 2006
, "-", 2006

........................................................................................................... 8
.................................................................................................................... 8
..................................................................................................... 9

................................................................................................................ 10
............................................................. 11
....................................................................................... 12
........................................................................................... 12
............................................................................. 13
PostgreSQL.............................................................................................................. 13
GNU SQL ................................................................................................................ 14
Beagle ...................................................................................................................... 14
.................................................................................................................. 14
............................................................................................... 15
........................................................................................................... 15
................................................................................................... 16
..................................................................................................... 17

I. ...................................... 19
1. , ........ 21
2. , ,
....................................................................................................... 23
(1) ..................................................................................... 24
.................................................................................................................... 25
..................................................................................................... 28
(2) ..................................................................................... 28
(3) ..................................................................................... 28

3. ............................................................. 34
................................................................................................................................... 35
( TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT) ................. 35
( DOUBLE FLOAT) .......................................... 37
NUMERIC (DECIMAL) ....................................................................................... 37
.................................................................................................................................... 38
CHAR ................................................................................................................... 38
VARCHAR ............................................................................................................ 39
TEXT BLOB .................................................................................................... 40
....................................................................................................................... 41
YEAR .................................................................................................................... 41
TIME..................................................................................................................... 41
DATE, DATETIME TIMESTAMP .................................................................. 42
................................................................................................................................. 45
ENUM () ........................................................................................ 45
SET () ................................................................................................. 46
............................................................................................ 48
, ................................................................................... 50
....................................................................................................... 50
.............................................................................................................. 50
............................................................................ 50
.................................................................. 51
....................................................................................................................... 51
ISAM ............................................................................................................................ 52
MyISAM ....................................................................................................................... 53
HEAP ........................................................................................................................... 53
BDB BerkeleyDB .................................................................................................. 53
InnoDB ......................................................................................................................... 54
MERGE ........................................................................................................................ 54

II. MYSQL .............................................................................................. 59


4. MySQL Windows........................................................ 61
5. MySQL ................................................................................... 68
6. .............. 70
III. . SQL............... 77
7. ............................................................... 79
................................................................................................................. 79
......................................................................................... 81
.................................................................................................................. 82
....................................................................................................... 83

....................................................................................................... 84
......................................................... 85
................................................................................. 85

8. ......................................................... 88
9. ........................................................... 98
10. .............................................................................. 103
.................................................................................................... 106
............................................................................ 108
..................................................................................................... 112

11. ............................................................................ 113


12. ( SELECT) ........................................... 116
...................................................................................................... 116
.................................................................................... 116
.................................................................................................. 117
........................................................................................................ 118
..................................................................................... 119
IN .............................................................................................................. 120
BETWEEN ... AND ................................................................................... 121
.............................................................................................. 122
..................................................................................................................... 125
.......................................... 126
................................................................................................. 130
....................................................... 130
.................................................................. 135
(JOIN) .......................................................... 138
.............................................................................. 141
.................................................................................. 142
EXISTS NOT EXISTS .............................. 144
IN NOT IN ............................................... 145
UNION ....................................................................................................... 147
.................................................................. 150
........................................................................................ 151

IV. PHP MYSQL ............................................................................. 153


13. PHP HTML ...................................................................................... 155
14. PHP .......................................................................... 157
...................................................................................................................... 157
integer................................................................................................................. 158
floating point ...................................................................................................... 158

string................................................................................................................... 158
object .................................................................................................................. 159
array ................................................................................................................... 160
........................................................................................................................... 160
...................................................................................... 160
............................................................................................... 161
............................................................................................................ 161
................................................................................................................. 161
..................................................................................................... 162
if / elseif ...................................................................................................................... 162
for foreach............................................................................................................... 163
while ........................................................................................................................... 164
switch ......................................................................................................................... 164
............................................................................................................................ 165
..................................................................................... 166
............................................................................................... 166

15. ..................................................... 167


16. ..................................................... 174
17. ......................................................... 180
................................................................................................ 183
1. MySQL......................... 185
2. PHP API MySQL ........................................ 187
mysql_affected_rows .......................................................................................................... 187
mysql_close ........................................................................................................................ 187
mysql_connect .................................................................................................................... 188
mysql_create_db ................................................................................................................ 189
mysql_data_seek ................................................................................................................ 189
mysql_db_query ................................................................................................................. 189
mysql_drop_db................................................................................................................... 189
mysql_errno ....................................................................................................................... 190
mysql_error ........................................................................................................................ 190
mysql_escape_string .......................................................................................................... 190
mysql_fetch_array.............................................................................................................. 190
mysql_fetch_assoc.............................................................................................................. 191
mysql_fetch_field ............................................................................................................... 191
mysql_fetch_lengths ........................................................................................................... 192
mysql_fetch_object............................................................................................................. 192
mysql_fetch_row ................................................................................................................ 192
mysql_field_flags ............................................................................................................... 193

mysql_field_len .................................................................................................................. 194


mysql_field_name .............................................................................................................. 194
mysql_field_seek ................................................................................................................ 194
mysql_field_table ............................................................................................................... 194
mysql_field_type ................................................................................................................ 195
mysql_free_result ............................................................................................................... 195
mysql_list_dbs .................................................................................................................... 195
mysql_list_fields ................................................................................................................. 195
mysql_list_processes .......................................................................................................... 196
mysql_list_tables ................................................................................................................ 196
mysql_num_fields............................................................................................................... 196
mysql_num_rows................................................................................................................ 196
mysql_pconnect .................................................................................................................. 196
mysql_ping ......................................................................................................................... 197
mysql_query ....................................................................................................................... 197
mysql_result ....................................................................................................................... 198
mysql_select_db ................................................................................................................. 198
............................................................................................. 198

3. .......... 200
3................................................................................................................................ 200
7................................................................................................................................ 200
8................................................................................................................................ 201
17.............................................................................................................................. 201

4. -..................................................... 204
.................................................................................... 205


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



() MySQL, . ,
MySQL,
. MySQL ,
.

MySQL
PHP, .
,
.
PHP
.


.
, . .
I " " ,
. ,
,
.
.
II "MySQL" MyQSL .
III " . SQL"
SQL,
, .
IV "PHP MySQL" ,
PHP , ""
MySQL.
,
MySQL.
, , .

MySQL PHP,
MySQL,
, ,
- .


MySQL. MySQL . , ,
.
().
.
MySQL (Michael Widenius,
Monty) . 1979 .
UNIREG. UNIREG
.
1994 . ,
UNIREG. ,
web-
. TcX,
UNIREG ,
mSQL 1995 . ,
, MySQL 1.0.
, : "
, MySQL. , "m".
(My). ,
MySQL".
MySQL
UNIX, Win32 OS/2. , MySQL 500 000 .
, II .

11

, ,
I, .



, , .
:

() , .

, . . , . ,
, , .
,
.
, . ,
, , , , . .
, . , :
1. ().
2. .
3. -.
4. .
5. .
6. .
, , (. 1).
, , . .
, , ()
, ().

12

. 1.


.
, .
, .
, , . .? ,
.
,
, . ,
"".
, . ,
. , , , , . .
.


MySQL . . .
web-.

.
-. ,
. HTML-,
,
. , web-

13

,
. ,
- .
web- ? web-. web- , (, -)
, .
,
, .
SQL (. III) , . ,
HTML- .
CGI-
Java.
HTML-.
, , .
IV.
PHP,
, .


SQL mSQL.
, PostgreSQL, GNU SQL, Beagle MySQL.
Open Source, . .
( ).

PostgreSQL
1980- (Michael Stonebreaker) (University of California at Berkeley) Ingres,
, . Ingres , .
, Ingres,

14

. Ingres
University Ingres
.

, Ingres.
,
, Ingres. Postgres.
Postgres, Ingres, ( ). Postgres
MySQL mSQL .
PostgreSQL http://www.postgresql.org.

GNU SQL
GNU . GNU
. .

.
- GNU SQL
SQL.
GNU SQL , .
GNU SQL http://www.ispras.ru.

Beagle
Beagle (Robert
Klein). GNU SQL, Beagle SQL .
Beagle http://www.beaglesql.org.


, :
 ;
 ;
 .

15

MySQL .
,
.


. , , ,
. :
.
( ) , .
(. 2).

111

II

III

112
...

. 2.

, -
, . , :
 ;
 ;
 (), .


. (, , ),
.
().

16


(. 3).

. .

. .

. .

321

873

125

. 3.


, . ,
(. 1).
1.

00001

JavaScript

00002

00003

XML

(. 2) .
2.

(.)

M-0001

ZyXEL

Omni 56K

1500

V-0033

LG

Flatron F700P

5000

A-0242

SVEN

SPS-611

800

17

I ,
.
.
:
 , -

;
 (. .

1, 2, ..., n),
. , , , ;
 (

);
 -

;


;
 ,

;


,
.
? ,
(. relation) ,
()
. . IBM
. . (E. F. Codd) 1968 .


,
. :
 (. entity) , (:

"");

18

 (. field) (: "-

", "");
 (. record) ;
 (. relationship) -

.
, . . ( ).


1.

2.

, ,

3.

, , () . .
, , , :
1. .
2. (, ).
3. .
4. .
5. (/), .
6. .
7. (. . , ,
).
8. .
2 3
, MySQL.

,

. , - .
, , .
, :
 ;
 , ;
 , ;
 ;
 ;
 ( ).

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

22

I.
1.1. ,

( )

12.12.2004

. ,
. 8, . 15

SMK321

12000

12.12.2004

. ,
. 32, . 3

(60 ),

(10 )

25

. ,
. 21, . 14

PS-911

4800

13.12.2004

14.12.2004

. ,
. 32, . 3

Tefal,

Tefal

2340

14.12.2004

. ,
. 45, . 26

Dect
S115

1200

...

...

...

...

...

...

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

. - ,
, . ,
, - .
, ,
. 1.1, .
, , .


, ,

,
. :
 ;
 ;
 .

, .
. , ,
, . .
( ) ,
. , , ,
.
, ,
. .
: , ,
, . . ? , (,
), .
. ,
, . . .
"" (. 2.1).

24

I.
2.1. ""

"", ""? , . .
. , " "
"", "".

, .
(. 2.2), , - .
2.2. ""

. , . 8, . 15

362-23-32

. , . 32, . 3

352-48-69

. , . 45, . 26

236-88-00

...

...

...

.
"" . . , IBM. . , , , .
.
, .

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

2. , ,

25

(. . 1.1), , "" , . . 1. ,
, , . "" . , .
(. 2.3).
2.3. ""

( )

Tefal

1145

SMK321

Sony

12 000

Dect S115

Dialon

1200

...

...

...

, 1.
, .


,
.
? , :
 ( );
 , NULL ( -

);
 .
(primary key).
,
. , "" (. 2.4).
, . .
. , ( , , ).

26

I.

(composite primary key), " " " ". .


2.4. ""

23

12

25

12

10

23

, . . .
, .
, (. . 2.2). "".
( )?
. ,

. . , ,
, , , . , ,
NULL.
, ""
(. 2.5).

.
2.5. ""

2. , ,

27

" ", .
() ,
. :
 (1:1) ,
;
 (1:) ,

;
 (:) ,
,
.
. "1:1"
. , .
, , ,
. .

. 2.1. "" ""

, . 2.1, "1:".
, . , "" "" " ".
, ,
, (foreign key). , "" " ".
, ( ), .

28

I.


, , . .
, ,
. ,
.
,
,
. , "", "" , .

(2)
, .
(2),

.
"" (. . 2.5) . . ,
( ), .

(3)
(3),
.
,
:
1. ( ), .
2. ( ) . (
), ,
.

2. , ,

29

3. ,
, .

(. 2.6 2.7).
2.6. "" 3

...

...

...

2.7. " " 3


. , . 34, . 40

954-87-23

. , . 123, . 23

941-85-25

. , . 12

654-78-22

...

...

...

" " (. 2.2).


, (,
). , .
, ,
. .
"". , . ,
. -,
(. 2.8).

30

I.

. 2.2. "" " "

2.8. ""

...

...

...

...

...

...


. , :
 : ;
 : "HTML 4.0. ";
 : 2004;
 : " ";
 : " ".

, 25 .
, ""
. . , ,
.
(. 2.9).
.
, ,
.

2. , ,

31

2.9. ""

...

...

, ""
, . ""
( ,
" "), (. 2.10).
2.10. ""

...

...

" " , .
"" " ".
, ,
(. 2.11) () (. 2.12).
2.11. ""

...

...

2.12. ""

...

...

"" "" "" " " " " .

32

I.

, , . . .
, . "" (. 2.13).
2.13. ""

...

...

...

, , , (. 2.14).
2.14. " "

...

...

...

, , , .
"" (. 2.15).
2.15. ""

...

...

...

...

...

, ,
(. 2.3).

2. , ,

. 2.3. ""

33


, , (, , . .). , .
, .
() .
, , .
, MySQL,
:
 (Numbers);
 (Text);
 (Date and Time);
 (Defined group).
. 3.1 .
3.1. MySQL

TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT


FLOAT, DOUBLE
NUMERIC, DECIMAL

CHAR
VARCHAR
TINYTEXT, MEDIUMTEXT, TEXT, LONGTEXT
TINYBLOB, MEDIUMBLOB, BLOB, LONGBLOB

3.

35
3.1 ()

DATETIME
TIMESTAMP
DATE
TIME
YEAR

ENUM
SET

MySQL ( 5 46) ( , 123,5).


.
( 1,34+14 2,533).
. .
.


( TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT)
TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT , (0). ,
(signed)
(unsigned).
 ,

. "" ().
 .

. ,
, UNSIGNED
.
field_name INT(length) UNSIGNED

36

I.

: field_name , length
( ). length
, . ,
field_name INT


field_name int(11)

, , length
, ,
.
.
 TINYINT(length) 0 255 128

127 . , , , . length,
, . , ,
TINYINT(2),
9 99 0 99 .
 SMALLINT(length) 0 65 535 32 768

32 767 .
 MEDIUMINT(length) 0 16 777 215

8 338 608 8 338 607 .


 INT(length) 0 4 294 967 295

2 147 483 648 2 147 483 647 .


 BIGINT(length) 0 18 446 744 073 709 551 615

9 223 372 036 854 775 808 9 223 372 036 854 775 808
. 8 .
, MySQL.
,
, MySQL
. , , , TINYINT,
300, 128
( ). , 300, 127.
TINYINT ,
300 300 0 255 .

3.

37


( DOUBLE FLOAT)
.
FLOAT(length, decimal) () . 3.402823466+38
1.17549435138 1.17549435138 3.402823466+38.
length ( ) ,
decimal , . ,
FLOAT(9,2) , :
999999.99

UNSIGNED, .
, FLOAT , MySQL .
DOUBLE(length, decimal)
(8 ). 1.7976931348623157E+308
2.2250738585072014E308, 0 2.2250738585072014E308
1.7976931348623157E+308. UNSIGNED,
. DOUBLE DOUBLE PRECISION
REAL.

NUMERIC (DECIMAL)
NUMERIC(length, decimal) DECIMAL(length, decimal) , . . DECIMAL , DOUBLE,
DECIMAL length decimal.
UNSIGNED, .
decimal , 0. length, 10.
. 3.2.
,
. . , . , TINYINT.

38

I.
3.2.

TINYINT

SMALLINT

MEDIUMINT

INT

BIGINT

FLOAT

DOUBLE

DECIMAL(length, decimal)
NUMERIC(length, decimal)

length + 2 ( decimal > 0)


length + 1 ( decimal = 0)
decimal + 2 ( length < decimal)

.
, (, '. , . 35, . 40').
,
. MySQL CHAR,
VARCHAR, TEXT BLOB.

CHAR
CHAR(length) . ( length)
1 255 ( MySQL 3.23 0
255).
. , MySQL ,
. .
MySQL . ,
BINARY:
field_name CHAR(length) BINARY

ASCII- ,
MySQL.

3.

39

VARCHAR
VARCHAR(length) . ( length)
1 255 . VARCHAR , ,
( 255).
. , VARCHAR,
. , , BINARY,
CHAR.
, CHAR VARCHAR ,
(. 3.3).
3.3. CHAR VARCHAR
CHAR(4)

VARCHAR(4)

''

'

'

''

'ab'

'ab

'

'ab'

'abcd'

'abcd'

'abcd'

'abcdef'

'abcd'

'abcd'

CHAR , (VARCHAR
) .
MyISAM ( ) .
CHAR(4) VARCHAR(4)
,
CHAR .
MySQL
.
 VARCHAR

CHAR.
 (VARCHAR,
TEXT BLOB),

CHAR VARCHAR. . MySQL VARCHAR

40

I.

. MySQL ,
.

TEXT BLOB
BLOB , .
(TINYBLOB, BLOB, MEDIUMBLOB, LONGBLOB),
.
TEXT , .
, BLOB
.
. 3.4.
3.4.

CHAR(length)

length

VARCHAR(length)

length + 1

TINYBLOB, TINYTEXT

length + 1 (length < 256)

BLOB, TEXT

64

MEDIUMBLOB, MEDIUMTEXT

16

LONGBLOB, LONGTEXT

, TEXT BLOB,
, .
, TEXT VARCHAR
(, BLOB VARCHAR BINARY). :
 BLOB TEXT , -

VARCHAR;
 BLOB TEXT DEFAULT

;
 BLOB TEXT MySQL 3.23.2

.
, ,
.

3.

41


MySQL
: YEAR, DATE, TIME, DATETIME, TIMESTAMP.
.
, '0'. ,
DATE '300' 'hallo' '0000-00-00'. , MySQL , '1998-02-31'.
, . MySQL . ,
012 031. 0 ,
MySQL DATE
DATETIME , , , '1980-00-00'
'1980-01-00' ( , ,
).
-- (, '1980-09-21'),
, (, '21-09-1980').
MySQL :
 0 69

2000 2069;
 70 99

1970 1999.

YEAR
YEAR . YYYY, YY.
1901 2155. 0. ,
(, " " " ").

TIME
TIME .
HH:MM:SS.
:

42

I.

 HH:MM:SS;
 HHMMSS (,

'12:22:10'); (, '129801'), '00:00:00';


 HHMM ;
 HH .
, , '100122' '10:01:22' ( HHMMSS). TIME
,
, 10.
'9:5:7' '09:05:07'.
'122210'

, TIME, ,
, . :
'1225', 12 25 ('12:25:00'), MySQL
'00:12:25' (12 25 ).

TIME '-838:59:59' '838:59:59'.


? , TIME
,
- , 24 .
, , . , '-900:00:00'
'900:00:00' '-838:59:59' '838:59:59' . '00:00:00'.

DATE, DATETIME TIMESTAMP


DATE , .
YYYY-MM-DD.
:
 YYYY-MM-DD;
 YY-MM-DD;
 YYMMDD;
 YYMMDDHHMMSS (, , ).
,
, 10. , '1980-5-9' -

3.

43

'1980-05-09'. '1000-01-01'
'9999-12-31'. '0000-00-00'.

MySQL.
 , , , . , ,
'10:11:12', ':' , , ,
'2010-11-12'. '12:55:35'
'0000-00-00', . . '55'
.
 MySQL :
0031, 0012, 10009999.
'0000-00-00'. , , '2004-02-31', . , , .
 , , , . . . MySQL :
0069 20002069;
7099 19701999.
DATETIME ,
, . MySQL
YYYY-MM-DD HH:MM:SS. '1000-01-01 00:00:00' '9999-12-31 23:59:59'.
TIMESTAMP(length)
INSERT ( ) UPDATE ( ). 19700101000000 - 2037 . "
" UNIX. NULL
. .
length () .
. length (. . ).
, length, , ,
length .

44

I.

TIMESTAMP 14 , TIMESTAMP (. 3.5).


3.5. TIMESTAMP

TIMESTAMP(14)

YYYYMMDDHHMMSS

TIMESTAMP(12)

YYMMDDHHMMSS

TIMESTAMP(10)

YYMMDDHHMM

TIMESTAMP(8)

YYYYMMDD

TIMESTAMP(6)

YYMMDD

TIMESTAMP(4)

YYMM

TIMESTAMP(2)

YY

length 6, 8, 12 14.
,
0 14, 14.
length . ,
TIMESTAMP, 0. TIMESTAMP
-.
,
TIMESTAMP. , ,
. , ,
, .
, TIMESTAMP, 4 (. 3.6).

,
:
 DATE DATETIME TIMESTAMP,


'00:00:00', . . DATE ;
 DATETIME TIMESTAMP DATE,

, . .
DATE .

3.

45

3.6.

YEAR

DATE

TIME

DATETIME

TIMESTAMP

MySQL : ENUM (), SET ().


.

ENUM ()
ENUM
(, ENUM('', '', '') ).
, ( 1).
('') NULL.
.
 ENUM (. . ,

), (
). "" , , 0.
 ENUM NULL, NULL

, .
ENUM NOT NULL,
.
65 535 .
256 , ,
(. . 3.8).
.
 ,
, , 1.
 0.
 NULL NULL.

46

I.

MySQL 3.23.51
.
, ENUM. , , , .
ENUM,
,
.
ENUM , . .
.

. , ENUM('', '') "" , "", ENUM('',


'') "" "."
, NULL
.

SET ()
SET
. (, SET('', '', '', '')). , .
, , SET('', '') NOT NULL,
:
 ''
 ''
 ''
 ','

SET 64 .
MySQL 3.23.51 SET .
MySQL SET , . SET , -

3.

47

,
.
SET, ,
, . ,
SET('a', 'b', 'c', 'd'). SET
( ) . 3.7.
3.7. SET

0001

0010

0100

1000

, ,
, .
, . , ,
,
.
, SET('a', 'b', 'c', 'd'), 'a,d',
'd,a' 'd,a,a,d,d' 'a,d'.
SET ,
.
SET .
NULL- .
SET
. N,
(N + 7) / 8 1, 2, 3, 4 8 .
SET 64 .
ENUM
. 255 . , 65 535 .
ENUM SET . 3.8.

48

I.
3.8. ENUM SET

ENUM('1', '2', ...)

1 2, ( 65 535)

SET('1', '2', ...)

1, 2, 3, 4 8
( 64)


1. MySQL?
2. SMALLINT?
3. YEAR?
, , MySQL. , "".
, .


,
. , .
? ,
. -,
, -, -. ,
.
.
, : ,
, .
, , .
, , . , .
, - (, . .), . , -

3.

49

, '2/20', . . 2 20 .
, . , , . , , . ,
. , , .
,
. ,
(, web-, PHP).
. , . FLOAT DOUBLE , . .
, , , .
DECIMAL(length,2), ( length). , , , , . : , /
.
, , 0 100 . , , (, BIGINT, ) .
, , .
(,
). , BIGINT. , ,
ALTER TABLE. ,
.
, UNSIGNED.
. 256 ,
CHAR, VARCHAR, TINYTEXT TINYBLOB. TEXT BLOB. ,
SET ENUM, .

50

I.

,
,
( MySQL 3.23.6).


MySQL
64 , (/), (\) (.).


( , )
"" , . (, shop_customer_information) , ,
. shop_cust
.
MySQL 64 (/), (\) (.).
MySQL , (. 1).


( 64). , 1, . . 1+1 .
,
:
SELECT * FROM 'select' WHERE 'select'.id_sel>20;

. 3.9 MySQL .
db_name table_name , . , table1 table2,
name, , ,
. . table1.name table2.name.
, ,
, ( ).

3.

51

3.9.

column_name

column_name

table_name.column_name

column_name table_name

db_name.table_name.column_name

column_name table_name
db_name (
MySQL 3.22)

'column_name'


MySQL ()
. ,
, MySQL,
.
Windows, UNIX .
, Windows ,
,
. , . .
reader, READER:
SELECT * FROM reader WHERE READER.id_reader=1;


, .


MySQL (. 3.10). MySQL, .
MySQL
FRM. ( ).
, MySQL, MyISAM.
ALTER TABLE. :
ALTER TABLE table_name TYPE = MyISAM;

52

I.
3.10. MySQL

ISAM

( )

MyISAM

( ISAM)

HEAP

BDB BerkeleyDB

InnoDB

MERGE

MyISAM,

, MySQL
(InnoDB BDB) (HEAP, ISAM, MERGE
MyISAM).
(Transaction-safe tables, TST):
 MySQL
,
,
;

COMMIT;
 ROLLBACK, ;
 , -

(
).
(Non-transaction-safe tables,
NTST):
 , . . ;
 , . .
;
 .
.

ISAM
, MySQL
5.0. ISM,
ISD.

3.

53

ISAM:
 ;
 ;
 256 ( );
 ,
, .
ISAM MyISAM:
 ISAM

;
 4 ;
 ;
 PACK_ISAM,
MYISAMPACK.

MyISAM
MyISAM MySQL 3.23.
ISAM
.
MYI (MYIndex), MYD (MYData). MyISAM / MYISAMCHK.
MyISAM MYISAMPACK,
.

HEAP
HEAP- -; .
,
MySQL , . HEAP
, ,
web-.

BDB BerkeleyDB
BDB MySQL
3.23.
BerkeleyDB
MySQL. BerkeleyDB

54

I.

, COMMIT () ROLLBACK () .
http://www.sleepycat.com.

InnoDB
InnoDB Innobase Oy (http://www.innodb.com).
MySQL , , . InnoDB
. .
InnoDB .
.
InnoDB , .

MERGE
MERGE () MySQL 3.23.25.
MERGE ( MRG_MyISAM) MyISAM, .
, . , ,
.
MERGE
( FRM) ( MRG). MRG-
( MYI), .
, MERGE:
 ;
 , ,

MERGE- , MERGE
;

3.

55

 ;
 ;
 .

:
 MERGE

MyISAM;
 AUTO_INCREMENT ( ) -

INSERT;
 REPLACE;


MERGE , ,
.

4. MySQL ?
5. ?
6. ?
, "" (library).
MyISAM ( MySQL
).
(. 3.111.18).
3.11. book ( "")

id_book

MEDIUMINT(5)
UNSIGNED

( 99 999)

title

VARCHAR(50)

( 50 )

year_issue

YEAR

id_author

SMALLINT(4)
UNSIGNED

(,
9999)

id_publisher

SMALLINT(3)
UNSIGNED

( 999)

id_section

TINYINT(2)
UNSIGNED

( 99)

56

I.
3.12. unit ( "")

id_unit

MEDIUMINT(6)
UNSIGNED

( 999 999)

id_book

MEDIUMINT(5)
UNSIGNED

( 99 999)

3.13. author ( "")


id_author

SMALLINT(4)
UNSIGNED

( 9999)

author

VARCHAR(60)

, (60
)

3.14. publisher ( "")


id_publisher

SMALLINT(2)
UNSIGNED

( 999)

publisher

VARCHAR(30)

( 30 )

3.15. section ( "")


id_section

TINYINT(2)
UNSIGNED

( 99)

section

VARCHAR(30)

( 30 )

3.16. reader ( "")


id_reader

MEDIUMINT(5)
UNSIGNED

( 99 999)

reader

VARCHAR(60)

, ( 60
)

id_addr

MEDIUMINT(5)
UNSIGNED

(
, !)

3.

57

3.17. address ( " ")


id_addr

MEDIUMINT(5)
UNSIGNED

(
)

address

VARCHAR(80)

( 80 )

phone

VARCHAR(19)

( )

3.18. abonement ( "")


id_note

MEDIUMINT(5)
UNSIGNED

( 99 999)

id_reader

MEDIUMINT(5)
UNSIGNED

id_unit

MEDIUMINT(6)
UNSIGNED

get_date

DATE

exp_date

DATE

,
UNSIGNED. .
,
AUTO_INCREMENT, NOT NULL . .
, , . 3.1.
,
. , , SQL.

58

I.

. 3.1. library ("")

II

MySQL
4.

MySQL Windows

5.

MySQL

6.

MySQL
Windows :
 Windows 95/98/ME/NT/2000/XP;
 - ZIP-;
 ,

.
-, WinZip http://www.winzip.com.
MySQL 100
.

MySQL
Windows
MySQL (http://www.mysql.com
/downloads/index.html http://www.mysql.ru). , MySQL
MySQL x.x -- Production release (recommended) ( MySQL 4.1).
- ().
MYSQL-X.X.X-WIN32.ZIP.
SETUP.EXE. MySQL Servers and
Clients (. 4.1).
Next > .
(. 4.2). Custom ( ) Next >.
(. 4.3) MySQL.
MySQL :.
Change C:\MYSQL\ .
, Next >.
(. 4.4) Install,
.
(. 4.5)
MySQL.com.
Skip Sign-Up ().
Next >.
MySQL Server (. 4.6).
Finish.

62

II. MySQL

. 4.1. , 1

. 4.2. , 2

4. MySQL Windows

. 4.3. , 3

. 4.4. , 4

63

64

II. MySQL

. 4.5. , 5

. 4.6. , 6 ()

4. MySQL Windows

65

, . (, )
,
.
, .
(. 4.7). Next >.

. 4.7. , 1

(. 4.8)
. Standard Configuration
Next > .
(. 4.9) Install As
Windows Service,
Windows. Next > .
(. 4.10).
Execute.
(. 4.11), MY.INI.

66

II. MySQL

. 4.8. , 2

. 4.9. , 3

4. MySQL Windows

. 4.10. , 4

. 4.11. , 5 ()

67

MySQL
MySQL. Windows
C:\MYSQL\BIN\ (. 5.1). , .
MYSQLD.EXE MySQL.
, .
MYSQLD.EXE bin
(. 5.1) .
.

. 5.1. C:\MYSQL\BIN\

5. MySQL

69

MYSQLSHOW.EXE
, . ,
, .
.
:
mysqlshow.exe [] [_ [_]]

[ ] , .

: -h, -u, -p. :


mysqlshow.exe hlocalhost uroot p12345



, ,
DOS. (Start) (Run).
cmd ( command)
. cd \mysql\bin <Enter> (. 6.1).

. 6.1. C:\MYSQL\BIN

, MYSQLSHOW - (. 6.2).
MySQL , . test ,
mysql.
mysqlshow mysql.
,
(. 6.3). .
mysqlshow mysql func (. 6.4).
MYSQL.EXE (
MySQL). mysql <Enter>.

6.

71

. 6.2. MYSQLSHOW

. 6.3. MYSQLSHOW

, ,
help. (shortcut),
(\) (. 6.5).
(;). (, help).
,
<Enter>, ,
';' (. 6.6).

72

II. MySQL

. 6.4. MYSQLSHOW

. 6.5. MySQL

';', . show
tables; mysql, use (. 6.7).

6.

73

. 6.6. ';'

. 6.7.

MySQL
exit quit (. 6.8).

. 6.8.

, MySQL.
MYSQLADMIN.EXE
. ,
.

74

II. MySQL

:
 create _ ;
 drop _ ;
 reload ;
 shutdown ;
 status .

( ,
MYSQLSHOW.EXE):
mysqladmin.exe [] []

MYSQLDUMP.EXE
(. 6.9). :
mysqldump.exe [] [_ [_]]

. 6.9. MYSQLDUMP ( )

6.

75

, , :
--add-drop-table ,
, (DROP TABLE IF EXISTS '_').

MySQL, 4.1,
, .

: mysqldump mysql>dump.txt <Enter>.


C:\MYSQL\BIN DUMP.TXT,
mysql.
.
(. 6.10). :
mysqladmin create db_name
mysql db_name<file_name

( )
( )

. 6.10.

, drop:
mysqladmin drop db_name

, create database db_name


(. 6.11).
, create database
(, mybase). (;)
<Enter>. .
, show databases;.
drop database db_name; (. 6.12).
, , .
library, .

76

II. MySQL

. 6.11. MySQL

. 6.12.

III

.
SQL
7.

8.

9.

10.

11.

12.

( SELECT)

MySQL (Structured Query Language, SQL). SQL


, , , . SQL
, MySQL .
- (GUI),
- " " SQL-.
SQL "" , . , ++, Java, PHP Perl, "
". SQL-:
SELECT title FROM book WHERE year_issue=2003

, : " , 2003". , .
SQL :
, ,

CREATE DATABASE,
DROP DATABASE,
ALTER DATABASE, USE

CREATE TABLE, CREATE INDEX,


DROP TABLE, DROP INDEX,
ALTER TABLE

INSERT, DELETE,
UPDATE, LOAD DATA,
REPLACE

BEGIN, COMMIT,
ROLLBACK,
SET AUTOCOMMIT

DESCRIBE (DESC), SHOW

SELECT,
UNION

GRANT,
FLUSH,
REVOKE

, MySQL.
, MySQL
.
SQL- , . ,
, , (
II). , (
, , ). , ( , . .) .



. SQL, .


CREATE TABLE.
CREATE TABLE:
CREATE TABLE _ (_, ...)

: _ , _ . MySQL 3.23
CREATE TABLE IF NOT EXISTS:
CREATE TABLE IF NOT EXISTS _ (_, ...)

, .
, .
(. II), :
CREATE TABLE mytable (...) TYPE=INNODB;

, , ,
MyISAM.
, , ( ):
 PRIMARY KEY , -

.
NOT NULL. .

80

III. . SQL

, , ,
PRIMARY KEY ( NOT NULL), PRIMARY KEY(_1,_2);
 NULL ( NULL,

NOT NULL, , NULL);

 NOT NULL (

).
;
NULL NOT NULL TIMESTAMP.
NULL
.

 KEY INDEX ( -

SELECT);

 ZEROFILL ,

. , smallint(5)
1, 00001;

 UNSIGNED ( );
 AUTO_INCREMENT . -

NULL () 0 AUTO_INCREMENT value+1, value . AUTO_INCREMENT


1. AUTO_INCREMENT,
. , MySQL 3.23

AUTO_INCREMENT. ;

 DEFAULT '' . DEFAULT

, .
DEFAULT, MySQL . NULL , NULL.
NOT NULL, :
,
AUTO_INCREMENT, 0. AUTO_
INCREMENT ;

7.

81

, TIMESTAMP, .
TIMESTAMP
;
, ENUM, . ENUM (
DEFAULT);
 BINARY , ( CHAR VARCHAR);
 UNIQUE . -

, , .


, .
.
(. 7.1).
7.1.
reader
id_reader

reader

id_addr

12

13

14

15

16

17

18

19

, ,
,
. (
), . . 7.2
id_addr reader.

82

III. . SQL
7.2. id_addr
id_addr
2
2
3
4
5
5
6
7

, 2,
. (3), . . .
- , - ,
,
.
. , , 1000 , 1000 . , ,
1000 1000 = 1 000 000 . ?!
MySQL , , WHERE. ,
.

, , . . , ,
.

7.

83


MySQL .
( MyISAM 32 500
). .
, .
, .
CHAR VARCHAR ( ), ,
. TEXT BLOB
( 255 ). .

:
KEY _ (_())

_() .
. 7.1.

. 7.1. 10 title

:
SHOW INDEX FROM _

:
 ;
 ;
 FULLTEXT .

CREATE TABLE,
CREATE INDEX ALTER TABLE (
).
:
ALTER TABLE _ ADD INDEX _ (_);

84

III. . SQL

:
ALTER TABLE _ ADD UNIQUE _ (_);

:
ALTER TABLE _ ADD PRIMARY KEY (_);

FULLTEXT:
ALTER TABLE _ ADD FULLTEXT (_);

_ ().
CREATE INDEX
( PRIMARY KEY):
CREATE INDEX _ ON _ (_);
CREATE FULLTEXT INDEX _ ON _ (_);
CREATE UNIQUE INDEX _ ON _ (_);

, , . 7.1,
(n).
:
CREATE TABLE mytable (first_name VARCHAR(30), last_name VARCHAR(30),
INDEX (first_name(), last_name(5)));

, , .
, .


. ,
. ,
, .
FULLTEXT .


DROP INDEX ALTER TABLE:
DROP INDEX _ ON _;
ALTER TABLE _ DROP INDEX _;

PRIMARY KEY:
ALTER TABLE _ DROP PRIMARY KEY;

, . , .

7.

85


, , ,
. , . ,
.
, , , .
, WHERE, ORDER BY
GROUP BY.
:
mysql> SELECT title, year_issue FROM book WHERE id_author>3;

title year_issue , id_author .


SELECT 12.

,
, . , ,
,
. (,
- 40% ), , ,
. , , (Male Female), , . .
.
, , . ,
. , , .


. :
DROP TABLE _ [,_...]

,
mysql> DROP TABLE reader;

, reader.

86

III. . SQL

, , .
IF EXISTS , .
. 7.2 . test ( ) , mytable, . SHOW
TABLES ,
. SHOW TABLES ,
.

. 7.2.

. 7.3.

7.

(. 7.3):
RENAME TABLE __ TO __


1. ?
2. MySQL?

87


ALTER
TABLE. , , , . ALTER TABLE MySQL (
RENAME) . , . ALTER TABLE
. , , , , , . .
:
ALTER TABLE _ 1 [,2...]

, :
 ADD _ ( _

, CREATE TABLE). .
FIRST, .
AFTER _, _.
ADD :

ADD FULLTEXT (_) FULLTEXT (,


MySQL 3.23.23);
ADD INDEX (_) ();
ADD PRIMARY KEY ;
ADD UNIQUE ;

8.

89

 ALTER _ SET DEFAULT | DROP DEFAULT

, , .
:
mysql> ALTER TABLE address ALTER city SET DEFAULT '-';

mysql> ALTER TABLE address ALTER city DROP DEFAULT;

 CHANGE __ _

(__ , _
, , CREATE TABLE);

 DROP _ . -

DROP INDEX _;
DROP PRIMARY KEY;
 MODIFY _ ;
 RENAME __ .

. test
(. 8.1) .

. 8.1.

ADD (. 8.2).
:
mysql> ALTER TABLE myuser ADD description text;

. 8.2.

90

III. . SQL

DESC _ ( DESCRIBE) , .
';'.
SQL (
). : desc _;

,
FIRST AFTER:
mysql> ALTER TABLE myuser ADD description text FIRST;
mysql> ALTER TABLE myuser ADD description text AFTER id_user;

CHANGE
. , :
mysql> ALTER TABLE myuser CHANGE description description TINYTEXT;

. 8.3. description

. , , , .

mysql> ALTER TABLE myuser CHANGE description comment TINYTEXT;

, . , CHANGE MODIFY.
.
mysql> ALTER TABLE myuser MODIFY description TINYTEXT;

. DROP :
mysql> ALTER TABLE myuser DROP desrcription;

8.

91

myuser description.
. 8.4.

. 8.4.

, . , DROP TABLE.
, RENAME
ALTER TABLE:
ALTER TABLE __ RENAME __;

RENAME TABLE:
RENAME TABLE __ TO __;

. 8.5. RENAME

92

III. . SQL

ALTER TABLE,
RENAME TABLE :
RENAME TABLE 1 TO _, 2 TO 1, _
TO 2;

,
.

, , .
,
. ,
C:\MYSQL\BIN (, LIBRARY.TXT)
- .
,
MYSQL.EXE . , '--'. 8.1
, library.
8.1
CREATE TABLE abonement (
id_note MEDIUMINT(5) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
id_reader MEDIUMINT(5) UNSIGNED,
id_unit mediumint(6) UNSIGNED,
get_date DATE,
exp_date DATE);
CREATE TABLE address (
id_addr MEDIUMINT(5) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
address VARCHAR(80),
phone VARCHAR(19));
CREATE TABLE reader (
id_reader MEDIUMINT(5) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
reader VARCHAR(60),
id_addr MEDIUMINT(5));
CREATE TABLE section (
id_section TINYINT(2) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
section VARCHAR(30));

8.

93

CREATE TABLE publisher (


id_publisher SMALLINT(3) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
publisher VARCHAR(30));
CREATE TABLE author (
id_author SMALLINT(4) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
author VARCHAR(60));
CREATE TABLE unit (
id_unit MEDIUMINT(6) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
id_book MEDIUMINT(5));
CREATE TABLE book (
id_book MEDIUMINT(5) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
title VARCHAR(50),
year_issue YEAR,
id_author SMALLINT(4) UNSIGNED,
id_publisher SMALLINT(3) UNSIGNED,
id_section TINYINT(2));

, ,
MYSQL.EXE (. 8.6).
exit:
mysql> exit
Bye
C:\mysql\bin>

. 8.6. LIBRARY.TXT

MYSQLSHOW.EXE ,
.

94

III. . SQL

()
, -
:
C:\mysql\bin> mysqldump -uroot --add-drop-table library>db_library.txt

8.2 DB_LIBRARY.TXT.
8.2
-- MySQL dump 8.23
--- Host: localhost
Database: library
---------------------------------------------------------- Server version 3.23.58-max-debug
--- Table structure for table 'abonement'
-DROP TABLE IF EXISTS abonement;
CREATE TABLE abonement (
id_note mediumint(5) unsigned NOT NULL auto_increment,
id_reader mediumint(5) unsigned default NULL,
id_unit mediumint(6) unsigned default NULL,
get_date date default NULL,
exp_date date default NULL,
PRIMARY KEY (id_note)
) TYPE=MyISAM;
--- Dumping data for table 'abonement'
---- Table structure for table 'address'
-DROP TABLE IF EXISTS address;
CREATE TABLE address (
id_addr mediumint(5) unsigned NOT NULL auto_increment,
address varchar(80) default NULL,
phone varchar(19) default NULL,
PRIMARY KEY (id_addr)
) TYPE=MyISAM;

8.
--- Dumping data for table 'address'
---- Table structure for table 'author'
-DROP TABLE IF EXISTS author;
CREATE TABLE author (
id_author smallint(4) unsigned NOT NULL auto_increment,
author varchar(60) default NULL,
PRIMARY KEY (id_author)
) TYPE=MyISAM;
--- Dumping data for table 'author'
---- Table structure for table 'book'
-DROP TABLE IF EXISTS book;
CREATE TABLE book (
id_book mediumint(5) unsigned NOT NULL auto_increment,
title varchar(50) default NULL,
year_issue year(4) default NULL,
id_author smallint(4) unsigned default NULL,
id_publisher smallint(3) unsigned default NULL,
id_section tinyint(2) default NULL,
PRIMARY KEY (id_book)
) TYPE=MyISAM;
--- Dumping data for table 'book'
---- Table structure for table 'publisher'
-DROP TABLE IF EXISTS publisher;
CREATE TABLE publisher (
id_publisher smallint(3) unsigned NOT NULL auto_increment,

95

96

III. . SQL

publisher varchar(30) default NULL,


PRIMARY KEY (id_publisher)
) TYPE=MyISAM;
--- Dumping data for table 'publisher'
---- Table structure for table 'reader'
-DROP TABLE IF EXISTS reader;
CREATE TABLE reader (
id_reader mediumint(5) unsigned NOT NULL auto_increment,
reader varchar(60) default NULL,
id_addr mediumint(5) default NULL,
PRIMARY KEY (id_reader)
) TYPE=MyISAM;
--- Dumping data for table 'reader'
---- Table structure for table 'section'
-DROP TABLE IF EXISTS section;
CREATE TABLE section (
id_section tinyint(2) unsigned NOT NULL auto_increment,
section varchar(30) default NULL,
PRIMARY KEY (id_section)
) TYPE=MyISAM;
--- Dumping data for table 'section'
---- Table structure for table 'unit'
-DROP TABLE IF EXISTS unit;
CREATE TABLE unit (
id_unit mediumint(6) unsigned NOT NULL auto_increment,

8.

97

id_book mediumint(5) default NULL,


PRIMARY KEY (id_unit)
) TYPE=MyISAM;
--- Dumping data for table 'unit'
--

, MySQL
(NULL), MyISAM, , -add-drop-table, DROP TABLE
IF EXISTS _.
, MySQL ,
. ,
MYSQL.EXE.
, -add-drop-table MySQL 4.xx .

,
- . , . .

1. ALTER TABLE ?
2.
?


LOAD DATA INSERT.
INSERT , LOAD
DATA , . .
INSERT:
INSERT [INTO] [IGNORE] [LOW PRIORITY | DELAYED]
_ [(_,...)] VALUES (,...);

: _ , ; ( (
, ); (_,...) ,
. ([]),
. , , . myuser:

,...)

myuser
id_user

login

password

...

...

...

(id_user login),
:
mysql> INSERT INTO myuser(id_user,login) VALUES(1,'login1');

, ,
( ). ,
:
mysql> INSERT INTO myuser VALUES(1,'login1','password1');

9.

99

INTO ( MySQL 3.22.5). LOW PRIORITY,


,
. DELAYED
, ,
.
- ,
,
MySQL .
, PRIMARY KEY
UNIQUE,
(. 9.1). IGNORE .

. 9.1.

, :
 NULL , NOT NULL;
, ;
 ,
; ;
 , '32 ba';
, ;
, 0;
 CHAR, VARCHAR, TEXT BLOB ,
; ;
 ,
; ,
.

100

III. . SQL

:
INSERT INTO _ SET _=[, _=,...];

INSERT , SET,
. ,
.

. 9.2. INSERT ... SET

SELECT,
:
mysql> SELECT * FROM reader;

LOAD DATA , :
LOAD DATA [LOCAL] INFILE '_.txt' [IGNORE | REPLACE]
INTO TABLE _


. ( C:\MYSQL\DATA\LIBRARY).
LOCAL , MySQL.
LOCAL .
:
1. '\n'.
2. .
, 1.TXT, , :
1
2
3

Denis
Oleg
Nina

1
2
3

9.

101

LOAD DATA
(. 9.3):
mysql> LOAD DATA INFILE '1.txt' INTO TABLE reader;

. 9.3. LOAD DATA

, IGNORE n LINES. , ,
:
id_reader reader
1
Denis
1
2
Oleg
2
3
Nina
3

id_addr


mysql> LOAD DATA INFILE '1.txt' INTO TABLE reader IGNORE 1 LINES;

.
IGNORE REPLACE , .
(, section) (. 9.4):
mysql> INSERT INTO section VALUES
-> (1,''),
-> (2,''),
-> (3,'');

, , .
, , . - DATA_FOR_LIBRARY.TXT INSERT . Win-

102

III. . SQL

dows-1251, ( ,
).
SQL (DELETE, UPDATE, SELECT)
. , :
C:\mysql\bin> mysql uroot library<data_for_library.txt

uroot , ,
, . , ,
, .

. 9.4. section

10


-
, , . .
PHP, .
DELETE:
DELETE FROM _ [WHERE ];

DELETE _ , WHERE . WHERE , . , ,


mysql> DELETE FROM reader;

reader (""),
. ?
.
_=''. ,
mysql> DELETE FROM reader WHERE id_reader=1;

" reader , id_reader


1". ( , . . id_reader
PRIMARY KEY).
(=) :

104

III. . SQL

 > (", "):


mysql> DELETE FROM book WHERE year_issue>2000;


2001 (. 10.1);

. 10.1. book

 >= (" "):


mysql> DELETE FROM reader WHERE id_reader>=25;

, 25;
 < (", ");
 <= (" ");
 <> != (" ):
mysql> DELETE FROM author WHERE id_author<>5;

, 5
( , . 10.2);
 IS NULL ( NULL) (. 10.3):
mysql> DELETE FROM reader WHERE reader IS NULL;

NULL ,
, . , NULL
;
NULL
(=, > !=).

10.

. 10.2. author

. 10.3. , NULL

. 10.4. reader, NULL

105

106

III. . SQL

 IS NOT NULL ( , NULL) (. 10.4):


mysql> DELETE FROM reader WHERE reader IS NOT NULL;


MySQL :
 LIKE '' ;
 NOT LIKE '' .

:
 '_' ;
 '%' .

MySQL .
, ,
'', (. 10.5):
mysql> DELETE FROM author WHERE author LIKE '%';

,
'%'. , .
. 10.6 10.7.

. 10.5. '%'

10.

107

, '',
(. 10.6):
mysql> DELETE FROM author WHERE author LIKE '%';

. 10.6. '%'

, '',
(. 10.7):
mysql> DELETE FROM author WHERE author LIKE '%%';

. 10.7. '%%'

108

III. . SQL

, ,
:
mysql> DELETE FROM author WHERE author LIKE '_ _ _ _ _ _ ';

'_'. ''
'' ,
(. 10.8).

. 10.8. '_ _ _ _ _ _ '


, , .
REGEXP NOT REGEXP . RLIKE NOT RLIKE.
:
 . () ;
 [...] ( ) , -

( ). , '[ab2]' 'a' 'b'


'2';
, . , , [a-z]

10.

109

, [0-9] .
, ,
[a-z0-9] .

 + . '[0-9]+' -

, 'a+'
'a', '.+'
;

 * . ,
'[a-z]*'

 ? ;
 {n} . ,
'[0-9]{4}'

 {n,} n ;
 {n,m} n m (. . -

);

 ^ . , '^[0-9]{4}' -

 $ . '[a-zA-Z]{2}$' -

, .

MySQL 3.23.4 REGEXP


. .
"" REGEXP , BINARY.

, . , .
mysql> DELETE FROM book WHERE title REGEXP BINARY '^[-]';

,
, '' (. 10.9).
mysql> DELETE FROM book WHERE title RLIKE '^.{3}$';

,
('') (. 10.10).
mysql> DELETE FROM book WHERE title RLIKE '[0-9]+';

, (. 10.11).

110

III. . SQL

. 10.9.

. 10.10. '^.{3}$'

mysql> DELETE FROM book WHERE title RLIKE '[-]+( [-]+)+';

, . '[-]+' ( , ),
'( [-]+)+'.
+, ,
. -

10.

111

, .
'' (. 10.12).

. 10.11. '[0-9]+'

. 10.12. '[-]+( [-]+)+'

TRUNCATE:
TRUNCATE [TABLE] _;

, .
TABLE MySQL 3.23.33.

112

III. . SQL


, (OR)
(AND). :
mysql> DELETE FROM address WHERE phone IS NULL OR phone NOT LIKE '+7%';
mysql> DELETE FROM book WHERE title=' ' AND year_issue=1993;

, phone NULL , '+7'.


' ' 1993.

11


() UPDATE:
UPDATE _ SET _1=1 [, _2=2, ...]
[WHERE ]

: _ , ;
; ;
, , .

, UPDATE _
_, , , .
, _=
. , - author
(. 11.1):
mysql> UPDATE author SET author='' WHERE id_author=3;

, MySQL .

(. 11.2):
mysql> UPDATE address SET address='. , 32/15', phone='320-54-54'
WHERE id_addr=2;

, 2. , , ,
.

114

III. . SQL

. 11.1. UPDATE

. 11.2.

:
UPDATE _ SET _=_+1 WHERE ;

, .
UPDATE _ SET _=_*2, _=_+1
WHERE ;

_ , .

11.

115

WHERE , .
(. . 11.2).
Rows matched: 1 Changed: 1 Warnings: 0

,
UPDATE . IGNORE , , .
:
UPDATE _ SET _= WHERE LIMIT n;

n LIMIT , .

12


( SELECT)

SELECT. .
, .


SELECT ( ):
SELECT * FROM _;

'*' , _.
, .
, , ,
.


. , , :
mysql> SELECT title, year_issue FROM book;

,
(. 12.1).
.

12. ( SELECT)

117

. 12.1.


.
. , , . , . DISTINCT.
mysql> SELECT DISTINCT title FROM book;

(. 12.2).

. 12.2.

118

III. . SQL


, SELECT, LIMIT, . . :
SELECT _ FROM _ LIMIT ;

LIMIT : . , ,
(. 12.3):
mysql> SELECT title FROM book LIMIT 5;

. 12.3.

, . LIMIT :
SELECT _ FROM _ LIMIT , ;

: , ,
; .
LIMIT ,-1,
, . LIMIT n
LIMIT 0,n.
LIMIT. :
mysql> SELECT title FROM book LIMIT 2,3;

. 12.4.
LIMIT n ORDER BY,
MySQL , n ,
, .

12. ( SELECT)

119

. 12.4. LIMIT offset, count


, - . :
SELECT ... WHERE

, ,
(. 12.5):
mysql> SELECT * FROM book WHERE id_author=1;

. 12.5.

120

III. . SQL

,
10. WHERE ,
.
.


. ,
, 2003 1995 , :
mysql> SELECT title, year_issue FROM book WHERE year_issue=2003
AND year_issue=1995;

.
, 2003, 1995 ,
. (. 12.6):
mysql> SELECT title, year_issue FROM book WHERE year_issue=2003
OR year_issue=1995;

, 2003
1995 .

. 12.6. OR

IN
(. 12.7):
mysql> SELECT title, year_issue FROM book WHERE year_issue IN(2003,1995);

12. ( SELECT)

121

. 12.7. IN

IN ("") , OR ( ). .
, NOT IN (" "):
mysql> SELECT title, year_issue FROM book WHERE year_issue
NOT IN(2003,1995);

, ,
.

BETWEEN ... AND ...


BETWEEN ... AND ... (" ... ...")
, -
.

. 12.8. BETWEEN ... AND ..

, ,
1990 2000 (. 12.8):

122

III. . SQL

mysql> SELECT title, year_issue FROM book WHERE year_issue


BETWEEN 1990 AND 2000;

NOT BETWEEN (" ")


(. 12.9).

. 12.9. NOT BETWEEN


,
. .
- , :
SELECT _1, _2, ... FROM _ ORDER BY _;

. ORDER
BY , , ( ).
1.

, NULL?
MySQL. MySQL 4.0.2 NULL
.
.
. , ,
:
mysql> SELECT * FROM book ORDER BY year_issue;

mysql> SELECT * FROM book ORDER BY 3;

12. ( SELECT)

123

. 12.10.

book, ()
(. 12.10).
, ( ).
(. 12.11):
mysql> SELECT title, year_issue FROM book ORDER BY title;

. 12.11.

ORDER BY :
mysql> SELECT title, year_issue FROM book ORDER BY title, year_issue;

124

III. . SQL


(,
" " 1985 , 2001 ) (. 12.12).

. 12.12.

.
, , , , .
BINARY:
SELECT * FROM _ ORDER BY BINARY _;

( ) DESC. :
mysql> SELECT title, year_issue FROM book ORDER BY title DESC;

. 12.13.

. 12.13.

12. ( SELECT)

125

, . :
mysql> SELECT title, year_issue FROM book ORDER BY title
DESC, year_issue ASC;

year_issue ASC (
, ).
:
mysql> SELECT title, year_issue FROM book ORDER BY year_issue
DESC LIMIT 1;

, ,
( ).
DESC , .
.

GROUP BY
, ,
GROUP BY.
GROUP BY
title book:
mysql> SELECT title FROM book GROUP BY title;

GROUP BY
title year_issue book:
mysql> SELECT title, year_issue FROM book GROUP BY title;

GROUP BY
, , title year_issue
book:
mysql> SELECT title, year_issue FROM book GROUP BY year_issue;

, - , , .
. 12.14.

126

III. . SQL

. 12.14. GROUP BY


HAVING . HAVING , WHERE .
GROUP BY. , .



SQL SELECT WHERE
.
, , .

12. ( SELECT)

127

. 12.1 ,
SQL, ( ) .
12.1.
/

+, -, *, /

, ,

()

BETWEEN(A,B,C)

(A>=B) AND (A<=C)

BIT_COUNT()

ELT(N,a,b,c)

a, N==1, b, N==2,
. . (a, b, ).
, ELT(2,'','','')
''

FIELD(S,a,b,c)

a, S==a, b, S==b,
. . (a, b, ).
, FIELD('', '', '',
'') ''

IF(A,B,C)

A ( 0 NULL), B, C

IFNULL(A,B)

A NULL, A,
B

ISNULL(A)

1, A==NULL

NOT, AND, OR

TRUE (1) FALSE (0)

SIGN()

, 1, 0 1

=, <>, <=, <, >=, >

TRUE (1) FALSE (0)

LIKE

TRUE (1) FALSE (0)

NOT LIKE

TRUE (1) FALSE (0)

REGEXP

TRUE (1) FALSE (0)

NOT REGEXP

TRUE (1) FALSE (0)

. 12.1
.
, SQL (. 12.2).

128

III. . SQL
12.2.

ABS(X)

() X

CEILING(X)

FLOOR(X)

ROUND(X)

EXP(X)

X ( )

LOG()

LOG10()

10

MOD()

POW(X,Y)

XY

SQRT(X)

RAND()

0 1

PI()

SIN(X)

X ( X )

COS(X)

TAN(X)

COT(X)

RADIANS(X)

DEGREES(X)


(. 12.3).
,
. , , (
).
. 12.4 .
12.3.

BIN(N)

N, N
(BIGINT). N NULL,
NULL

12. ( SELECT)

129
12.3 ()

OCT(N)


N, N . N NULL, NULL

HEX(N)

N , N, N
(BIGINT).
N ,
N, N
2

CONCAT()

INTERVAL(A,a,b,c,d)

1, A==a, 2,
A==b, . . (A, a, b, c, d ).
, 0

INSERT(str,pos,len,newstr)

str,
len, pos, newstr

LCASE(S)

UCASE(S)

LEFT(str,len)

len str

RIGHT(str,len)

len
str

MID(str,pos,len)

len
str, pos

LENGTH(str)

str

TRIM(str)

str

LTRIM(str)

str

RTRIM(str)

str

LOCATE(A,B)

LOCATE(A,B,C)

SUBSTRING(str,pos,len)

len
str, pos

130

III. . SQL
12.4.

CURTIME()

HH:MM:SS HHMMSS. , :
, SELECT
CURTIME()+0; 165651 ();
, SELECT
CURTIME(); '16:56:51' ()

CURDATE()

YYYY-MM-DD YYYYMMDD

DATABASE()

VERSION()

MySQL

USER()

, (login)

PASSWORD(str)

() "" ,
str


, . 12.5,
GROUP.
12.5.

AVG()

SUM()

COUNT()

MIN()

MAX()

SQL-,
GROUP BY, . , , : SUM(value/10).


COUNT() (
NULL) , SELECT (. 12.15).
mysql> SELECT COUNT(id_book) FROM book;

12. ( SELECT)

131

. 12.15. COUNT()

COUNT(*) ,
NULL. ,

WHERE.
mysql> SELECT COUNT(*) FROM book;

, COUNT().
, book,
(. 12.16):
mysql> SELECT COUNT(DISTINCT title) FROM book;

. 12.16. COUNT(DISTINCT )

132

III. . SQL

,
(. 12.17):
mysql> SELECT title, COUNT(id_book) FROM book GROUP BY title;

. 12.17. COUNT() GROUP BY

, . . title.
MIN() MAX() (. 12.18). , .

. 12.18. MIN() MAX()

CONCAT(1,2,...) ("" ) (. 12.19).

12. ( SELECT)

133

,
.

. 12.19. CONCAT()

, NULL, NULL.
CONCAT_WS(,1,2,...)
CONCAT(), "" , , .
,
RAND(). . , ,
, , . ,
mysql> SELECT RAND();

0,031077887891864.

mysql> SELECT RAND();

0,004335573971584.

mysql> SELECT RAND(4);

0,40613597483014.

134

III. . SQL


mysql> SELECT RAND(4);

0,40613597483014.

SELECT ORDER BY. ,
title book (. 12.20):
mysql> SELECT title FROM book ORDER BY RAND() LIMIT 1;

. 12.20. RAND

. 12.21. REVERSE()

12. ( SELECT)

135

RAND() WHERE, WHERE.


REVERSE() "" (. 12.21).
REPEAT(,) , , . ,
mysql> SELECT REPEAT('', 3);

''.



. , ,
() , .
,
, book author.
_._
, , (
, ).
table1 table2 :
mysql> SELECT table1.*, table2.* FROM table1, table2;

, reader address
(. 12.22):
mysql> SELECT reader.*, address.* FROM reader, address;

. 12.22.

136

III. . SQL

. . . 12.22
. , . . . 3 .
100 , 100 100 = 10 000 . ,
, WHERE, (. 12.23).
:
mysql> SELECT reader.*, address.* FROM reader, address WHERE
reader.id_addr=address.id_addr;

. 12.23. WHERE

. , :
mysql> SELECT book.title, author.author FROM book, author WHERE
book.id_author=author.id_author;


(. 12.24).
, , book
(id_author), author (. . ), .


, (. 12.25). -

12. ( SELECT)

137

, , . .
.

. 12.24. book author

. 12.25. book author

. 12.26.


(. 12.26). , ,
. , , , :
mysql> SELECT title, reader, address, get_date, exp_date FROM book,
reader, abonement, address, unit WHERE book.id_book=unit.id_book

138

III. . SQL

AND unit.id_unit=abonement.id_unit
AND reader.id_reader=abonement.id_reader
AND reader.id_addr=address.id_addr;

, , WHERE, OR AND.
AND, . . .
FROM unit, . , - . unit abonement book, ,
abonement, , book.

(JOIN)
(equi-join). FROM, (,).
. JOIN CROSS JOIN ','.
mysql> SELECT book.title, author.author FROM book JOIN author WHERE
book.id_author=author.id_author;
mysql> SELECT book.title, author.author FROM book CROSS JOIN author WHERE
book.id_author=author.id_author;

,
. 12.25.
STRAIGHT_JOIN , , .
, FROM.
STRAIGHT_JOIN SELECT:
SELECT STRAIGHT_JOIN ... FROM 1, 2,...
SELECT ... FROM 1 STARIGHT_JOIN 2 STRAIGHT_JOIN 3 ...

, , . .

, .
, -

12. ( SELECT)

139

, , ,
. , , . , .

table1 table2 (. 12.27).

. 12.27. table1 table2

(. 12.28),
, . . id :
mysql> SELECT table1.*, table2.* FROM table1, table2 WHERE
table1.id=table2.id;

. 12.28.

.
LEFT JOIN, ON ( WHERE).

140

III. . SQL

LEFT JOIN RIGHT JOIN


.

( RIGHT JOIN):
mysql> SELECT table2.*, table1.* FROM table2 LEFT JOIN table1
ON table2.id=table1.id;

. 12.29. LEFT JOIN

(. 12.29) ,
table2, table1. NULL.
, .
WHERE:
mysql> SELECT table2.* FROM table2 LEFT JOIN table1
ON table2.id=table1.id WHERE table1.id IS NULL;

table2 (. 12.30).

. 12.30.

12. ( SELECT)

141

ON ,
, . USING().
ON, , , .
, (. 12.31):
mysql> SELECT table2.*, table1.* FROM table2 LEFT JOIN table1 USING(id);

. 12.31. USING()

, , , .
library. LEFT JOIN,
, , :
mysql> SELECT unit.id_unit FROM unit LEFT JOIN abonement USING(id_unit)
WHERE abonement.id_unit IS NULL;

INNER JOIN , ON. .


mysql> SELECT table1.*, table2.* FROM table1, table2 WHERE
table1.id=table2.id;
mysql> SELECT table1.*, table2.* FROM table1 INNER JOIN table2
ON table1.id=table2.id;


() ,
WHERE (HAVING) SELECT , WHERE.
WHERE (HAVING)

142

III. . SQL

. . , ,
, ,
.
MySQL 4.1. (4.0)
.
.
.
WHERE (HAVING) IN, EXISTS
(=, <>, <, <=, > >=).
" ".
. , ,
. .
. , ,
, ( ). ,
.
. ., ,
( ).
, SQL
, . ,
, -.
. , . . (
), . ,
.


SELECT , SELECT.
:
mysql> SELECT title FROM book WHERE id_book=(SELECT id_book FROM book
WHERE id_author=1 and year_issue=2001);

12. ( SELECT)

143

. 12.32.

, ,
(. 12.32). , (. 12.33).

. 12.33.

SELECT
LIMIT 1.
WHERE - . , ,
, :
mysql> SELECT * FROM book WHERE year_issue=MIN(year_issue);

. 12.34.

144

III. . SQL

, . . WHERE . . :
mysql> SELECT * FROM book WHERE year_issue=(SELECT MIN(year_issue)
FROM book);

. 12.34.


EXISTS NOT EXISTS
,
SELECT, ,
, .
,
.
table1 table2,
(. . 12.27).
, :
mysql> SELECT id FROM table1 WHERE EXISTS (SELECT * FROM table2 WHERE
table1.id=table2.id);

,
.

_._, , . .
.

""
"", . . - ( , ). ,
, , "". :
mysql> SELECT id FROM table1 WHERE EXISTS (SELECT 1 FROM table2 WHERE
table1.id=table2.id);

NOT EXISTS , . . ,
, (. 12.36):

12. ( SELECT)

145

mysql> SELECT txt FROM table2 WHERE NOT EXISTS (SELECT * FROM table1
WHERE table1.txt=table2.txt);
mysql> SELECT id FROM table2 WHERE NOT EXISTS (SELECT * FROM table1
WHERE table1.id=table2.id);

. 12.35. EXISTS

. 12.36. NOT EXISTS


IN NOT IN
: SELECT ,
SELECT. (. 12.37 12.38):

146

III. . SQL

mysql> SELECT txt FROM table2 WHERE txt NOT IN (SELECT txt FROM table1);
mysql> SELECT id FROM table2 WHERE id NOT IN (SELECT id FROM table1);
mysql> SELECT id FROM table1 WHERE id IN (SELECT id FROM table2);

. 12.37. NOT IN

. 12.38. IN

,
EXISTS NOT EXISTS. , , (
MySQL 4.1). :
mysql> SELECT title FROM book WHERE id_book=(SELECT id_book FROM unit
WHERE id_unit=20);

, :
mysql> SELECT title FROM book,unit WHERE book.id_book=unit.id_book and
unit.id_unit=20;

MySQL 4.1 , ,
,

12. ( SELECT)

147

, , . . .

UNION
UNION, MySQL 4.0.0, SELECT . SELECT
.
UNION .
 -

SELECT.
SELECT UNION ,
.

 UNION -

(
DISTINCT).

 ORDER BY

SELECT. .

 ,

UNION, SELECT, UNION:


mysql> SELECT title FROM book UNION SELECT author FROM author;


(. 12.39) , ,
.
,
. (. 12.40) :
mysql> SELECT id_author, year_issue FROM book UNION SELECT id_author,
author FROM author;
mysql> SELECT id_author, year_issue FROM book UNION SELECT author,
id_author FROM author;

, book, , UNION.

148

III. . SQL

. 12.39. UNION

, UNION
. , ALL UNION:
mysql> SELECT id_author, year_issue FROM book UNION SELECT author,
id_author FROM author;

ALL
. 12.40. 1
id_author 2003 year_issue.
ORDER BY SELECT, SELECT ORDER BY .
UNION
LIMIT n. :
mysql> SELECT * FROM table1 UNION SELECT * FROM table2 LIMIT 1;

. SELECT, :
mysql> (SELECT * FROM table1 LIMIT 1) UNION (SELECT * FROM table2
LIMIT 1);

, , , . UNION MySQL 4.0,


, .
:

12. ( SELECT)
SELECT
FROM
INSERT
...
SELECT

TEMPORARY TABLE tmp_table TYPE=HEAP SELECT ...


table1 WHERE...;
INTO tmp_table SELECT ... FROM table2 WHERE...;
* FROM tmp_table;

. 12.40. UNION

149

150

III. . SQL

MySQL (TEMPORARY) . HEAP, , . , DROP TABLE


, .
3.23,
TEMPORARY HEAP.


MySQL, 4, .
mysql> DELETE table1 FROM table1, table2 WHERE table1.id=table2.id;

table1,
table2. FROM ,
, WHERE .
(, ):
mysql> DELETE table1, table2 FROM table1, table2 WHERE
table1.id=table2.id;

:
mysql> DELETE table1 FROM table1 LEFT JOIN table2 ON table1.id=table2.id
WHERE table2.id IS NULL;

mysql> DELETE FROM table1 USING table1, table2 WHERE table1.id=table2.id;


mysql> DELETE FROM table1, table2 USING table1, table2 WHERE
table1.id=table2.id;
mysql> DELETE FROM table1 USING table1 LEFT JOIN table2 ON
table1.id=table2.id WHERE table2.id IS NULL;

, 4.0.2.

UPDATE ,
DELETE. :
mysql> UPDATE table1, table2 SET table1.txt=table2.txt WHERE
table1.id=table2,id;

12. ( SELECT)

151


SQL,
, .
. ,
MySQL SQL,
.
. ,
.
commit () rollback ().
- ,
.
, .
MySQL BDB InnoDB.

152

III. . SQL

IV

PHP MySQL
13.

PHP HTML

14.

PHP

15.

16.

17.

PHP , web-. 1995


(Rasmus Lerdorf). PHP
Personal Home Page ( ),
PHP Hypertext Preprocessor
( PHP). PHP HTML-
. PHP, MySQL,
(open-source).
PHP MySQL , , . PHP
PHP web- (, Apache).

13

PHP HTML
PHP () web-, - ().
( . script) PHP-, HTML-.
HTML- , PHP- , . , PHP-. PHP
, .
PHP- HTML
, PHP-.
PHP :
 <?php PHP_ ?> ;
 <? PHP_ ?> (

);
 <script language="php"> PHP_ </script>

JavaScript.
, PHP-, PHP.
PHP- .
Linux PUBLIC_HTML. Windows, Apache web-, HTDOCS.
IIS web- WWWROOT.
, localhost .
Apache.
HTTPD.CONF , Apache PHP. :

156

IV. PHP MySQL

AddType application/x-httpd-php .php


ScriptAlias /__php__/ "c:/php/"
Action aplication/x-httpd-php /__php__/php.exe

, PHP
:.

PHP
:
<?php
phpinfo();
?>

TEST.PHP . . 13.1 .

. 13.1. PHP ,

14

PHP
()
(;). ,
. .
PHP ( ,
. .), .
, PHP-, HTML-.
, .
(//) (#), a "" (/* */).

PHP ($).
, (_) (_). , . . $a $A . ,
. (. . , ) .
PHP :
 integer
 floating point
 string

158

IV. PHP MySQL

 object
 array

"" VAR:
VAR $some_var;

, :
$some_var="value";

integer
integer
2 +2 , . :
$var1=100;
$var2=0144;
$var3=0x64;

/* */
/* */
/* */

floating point
floating point ().
:
$var1=2.34;
$var2=234e1;

string
( string) ,
. () . ,
. , .
:
$var="23";
$str1=' $var';
$str2=" $var";

:
$var
23

14. PHP

159

, .
, (\)
(").
$str1=" """;

, (\)
$str1=" \"\"";

(\)
.

. 14.1 Escape- ( ), .
14.1. Escape-, PHP
Escape-

\n

\r

\t

\\

(\)

\"

(")

\$

($)

\0

\x

object
( object) . . .
PHP (http://php.net)
PHP.

160

IV. PHP MySQL

array
array . PHP
:
 ;
 ().
, , ,
:
$myarr=array("value1", "value2" , "value3", "value4");

, , (
0). , $myarr[0] "value1", $myarr[3] "value4".
, : $myarr[]="value5";
:
$myhash=array('size'=>'large', 'style'=>'italic', 'family'=>'Arial');

PHP :
 ;
 ;
 ;
 ;
 .


. 14.2 .
14.2.

$a+$b

$a $b

$a-$b

$a $b

$a*$b

$a $b

$a/$b

$a $b

$a%$b


$a $b

14. PHP

161


(. 14.3) , (true)
(false).
14.3.

and &&

$a and $b
$a && $b

or ||
not !

true,

$a || $b

true,

not $a

$a or $b

!$a

(.) (
). :
<?php
$a='';
echo ' '.$a;
?>

<?php
$h=12;
$m=35;
$time=$h.':'.$m;
echo $time;
// 12:35
?>


true false.
. 14.4.

162

IV. PHP MySQL


14.4.

==

!=

>

<

>=

<=


PHP .
if, for, while, switch .

if / elseif
.
. :
<?php
if(1)
{
1;
}
elseif(2)
{
2;
}
else
{
;
}
?>
1 2 , 1 if 2 elseif . , , else ("").

14. PHP

163

for foreach
for
().
<?php
for(1; 2; 3)
{

}
?>

: 1 ; 2 (),
FOR ; 3
( ).
(echo ,
):
<?php
echo "<select name='num'>\n";
for($i=0;$i<10;$i++)
{
echo "<option>$i</option>\n";
}
echo "</select>";
?>

. 14.1.
FOREACH
.
<?php
foreach($array as $value)
{
PHP-
}
?>

:
<?php
foreach($hash as $key=>$value)
{
PHP-
}
?>

164

IV. PHP MySQL

. 14.1. PHP

while
while , . , .
<?php
while()
{

}
?>

switch
switch if
.
( )
.
switch:
<?php
switch()
{

14. PHP

165

case 1:
1;
break;
case 2:
2;
break;
...
default:
__;
}
?>

. , ,
switch. PHP
switch break. break
case, .
(, break
).
__ , ,
. default
case.

:
<?php
switch($a)
{
case 1: echo "i 1"; break;
case 2: echo "i 2"; break;
case 3: echo "i 3"; break;
}
?>

.
, , . PHP
:
 , ();
 () .

166

IV. PHP MySQL


,
. .
,
( ).
. , , ,
.
PHP- :
function _(_);
{
;
}

: _ , ; _
, (
);
( , ).


, ,
.
,
. () .
PHP (
http://php.net).

15


, PHP MySQL
web-.
PHP-, MySQl,
.

15.1 PHP-.
15.1. PHP-
<html>
<head>
<title> </title>
</head>
<body bgcolor="#ffffff">
<h3> </h3>
<?php
#
$id_con=mysql_connect("localhost", "root", "")
or die(" ");
#
mysql_select_db("library") or die(" ");
#
$res_id=mysql_query("select * from reader") or die(" ");
#
while($mr=mysql_fetch_row($res_id))
{
echo "$mr[1]<br>";
}

168

IV. PHP MySQL

mysql_close($id_con);
?>
</body>
</html>

:
1. MySQL. mysql_connect(), , . $id_con . " ".
2.

2. mysql_select_db() library .
3. ,
mysql_query(). SQL-, reader. $res_id
,
.
4. mysql_fetch_row().
( $mr). , SQL-. : (
id_reader), ( reader),
( id_addr).
reader. ,
while, mysql_
fetch_row(),
( ). ,
, reader.
, .
( )
.
5. mysql_close(), ( ) (. 15.1).

15.

169

. 15.1.

, . .
web- author
, .
, DBCONNECT.PHP .
<?php
$id_con=mysql_connect("localhost", "root", "")
or die(" ");
mysql_select_db("library") or die(" ");
?>


. .
AUTHOR_LIST.PHP ( 15.2),

(<select>). , .

DBCONNECT.PHP.

170

IV. PHP MySQL

15.2. AUTHOR_LIST.PHP
<?php
require "dbconnect.php";
?>
<html>
<head>
<title> </title>
</head>
<body>
<?php
$res_id=mysql_query("select * from author")
or die(mysql_error());
#
$num=mysql_num_rows($res_id);
echo " : <b>$num</b>";
?>
<h3> </h3>
<form method="post">
<select name="auth_list">
<?php
while($am=mysql_fetch_row($res_id))
{
echo "<option value='$am[0]'>$am[1]</option>\n";
}
?>
</select>
</form>
</body>
</html>

(. 15.2).
,
( ).

. ,
(. 15.3).
15.3 .

15.

. 15.2.

. 15.3.

171

172

IV. PHP MySQL

15.3.
<form method="post" action="add_author.php">
<select name="auth_list">
<?php
while($am=mysql_fetch_row($res_id))
{
echo "<option value='$am[0]'>$am[1]</option>\n";
}
?>
</select>
<br>
<input type="text" name="new_author">
<input type="submit" name="send" value=" ">
</form>

. , ,
action="add_author.php". ,
,
.
( 15.4) .
15.4.
<?php
require "dbconnect.php";
if(isset($_POST['new_author']))
{
$query="insert into author values('','".$_POST['new_author']."')";
if(mysql_query($query))
{
echo " ";
}
else
{
echo mysql_error();
}
}
?>

" ". AUTOR_LIST.PHP .


(. 15.4).

15.

173

. 15.4.

,
require() DBCONNECT.PHP ( ). ,
. ,
,
(, ).
require() include().
, , . include() (Warning!), require() (Fatal Error).
, require(), ,
. include() .
die().
. exit().

16


MySQL .
mysql_query() SQL- , :
$result_id=mysql_query("");

$query="";
$result_id=mysql_query($query);

( SELECT) FALSE . , DELETE, INSERT, UPDATE, REPLACE, TRUE, , FALSE . TRUE ,


. , :
$result_id=mysql_query("delete from reader where id_reader=35");
if($result_id)
{
echo " 35 ";
}
else
{
echo " ";
}

DELETE TRUE,
( ). . -:

16.

175

$result_id=mysql_query("delete from reader where id_reader=35");


if(!$result_id)
{
echo " ";
}
else if(mysql_affected_rows()<1)
{
echo " 35 ";
}
else
{
echo " 35 ";
}

mysql_affected_rows(), .
mysql_query() ,
. .
SELECT mysql_fetch_row() .
, (. 2).
, , :
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result
resource in path/script_name.php on line n.

, :
$result_id=mysql_query("select * from reader");
if(!$result_id)
{
echo " ";
}
else
{
$num=mysql_num_rows($result_id);
echo " : $num";
}

, :
 ;
 (,
);

176

IV. PHP MySQL

 ;
 - MySQL.

'@'. :
$connect_id=@mysql_connect("host", "login", "password");

/ error_reporting(), . :
 E_ALL ;
 E_ERROR ;
 E_WARNING ;
 E_PARSE ;
 E_NOTICE ;
 E_CORE_ERROR ;
 E_CORE_WARNING ;
 E_COMPILE_ERROR ;
 E_COMPILE_WARNING ;
 E_USER_ERROR , ;
 E_USER_WARNING , ;
 E_USER_NOTICE , .

error_reporting()
:
error_reporting(E_PARSE | E_NOTICE);

, . .
SQL-. E_NOTICE .
mysql_error().
,
mysql_free_result():
mysql_free_result($result_id);

, PHP .
,
.

16.

177

.
, . , 16.1 READER_LIST.PHP ( , , - ).
16.1
<html>
<head>
<title> </title>
</head>
<body>
<?php
#
require "dbconnect.php";
#
if(isset($_POST['send']))
{
# "address"
$query1="insert into address
values('', '".$_POST['addr']."','".$_POST['phone']."')";
$res_id1=mysql_query($query1);
/* , .
*/
$query2="select max(id_addr) from address";
$res_id2=mysql_query($query2);
# $addr_mas
$addr_mas=mysql_fetch_row($res_id2);
/* ,
reader */
$query3="insert into reader
values('', '".$_POST['name']."','".$addr_mas[0]."')";
$res_id3=mysql_query($query3);
}
#
echo "<table border='1'>\n";
echo "<tr><th></th><th></th><th></th></tr>\n";
#
$res_id=mysql_query("select reader, address, phone from reader, address
where reader.id_addr=address.id_addr ");

178

IV. PHP MySQL

#
while($reader_mas=mysql_fetch_row($res_id))
{
echo "<tr>
<td>$reader_mas[0]</td>
<td>$reader_mas[1]</td>
<td>$reader_mas[2]</td>
</tr>\n";
}
?>
</table>
<form method="post">
<br>
<input type="text" name="name"><br>
<br>
<input type="text" name="addr"><br>
<br>
<input type="text" name="phone"><br>
<input type="submit" name="send" value="">
</form>
</body>
</html>

, URL
http://localhost/reader_list.php.

(. 16.1).
(, =
, = . , 21/7, = 540-40-80)
. ,
(. 16.2).

16.

. 16.1.

. 16.2.

179

17


, $_POST['_'].
$_POST

(), , POST. GET $_GET.

.
PHP (PHP.INI) register_
globals=On. . , - address,
$address,
. .
, . . ,
.
PHP : register_globals=Off.
, , 'send':
if(isset($_POST['send']))

, .
(submit) . , - ,
<Enter> , .
, , , . . . :
<input type="hidden" name="_" value="_">

17.

181

:
<form method="POST">
<input type="text" name="name">
<input type="hidden" name="send" value="yes">
<input type="submit" value="Ok">
</form>

, . . , (_ = _)
, . .
URL.
, , , . PHP . , :
http://www.mywebsite.ru/script.php?parameter=value

, '&'.
http://www.mywebsite.ru/script.php?parameter1=value&parameter2=value

,
, . , 17.1
TEST_LINK.PHP .
17.1
<html>
<head>
<title> URL</title>
</head>
<body>
<!-- -->
<a href="test_link.php?action=1"> 1</a>
<br>
<a href="test_link.php?action=2"> 2</a>
<br>
<?php
if($action==1)
{
echo " 1";
}

182

IV. PHP MySQL

if($action==2)
{
echo " 2";
}
?>
</body>
</html>

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

1. ( ).
2. () .

1.


MySQL

2.

PHP API MySQL

3.

4.

MySQL
, MySQL .
ADD
ALL
ALTER
ANALYZE
AND
AS
ASC
ASENSITIVE
BEFORE
BETWEEN
BIGINT
BINARY
BLOB
BOTH
BY
CALL
CASCADE
CASE
CHANGE
CHAR
CHARACTER
CHECK
COLLATE
COLUMN
CONDITION
CONNECTION
CONSTRAINT

CONTINUE
CONVERT
CREATE
CROSS
CURRENT_DATE
CURRENT_TIME
CURRENT_TIMESTAMP
CURRENT_USER
CURSOR
DEFAULT
DATABASE
DATABASES
DAY_HOUR
DAY_MICROSECOND
DAY_MINUTE
DAY_SECOND
DEC
DECIMAL
DECLARE
DELAYED
DELETE
DESC
DESCRIBE
DETERMINISTIC
DISTINCT
DISTINCTROW
DIV

DOUBLE
DROP
DUAL
EACH
ELSE
ELSEIF
ENCLOSED
ESCAPED
EXISTS
EXIT
EXPLANE
FALSE
FETCH
FLOAT
FOR
FOR
FORCE
FOREIGN
FULLTEXT
GOTO
GRANT
GROUP
HAVING
HIGH_PRIORITY
HOUR_MICROSECOND
HOUR_MINUTE
HOUR_SECOND

186
IF
IGNORE
IN
INDEX
INFILE
INNER
INOUT
INSENSITIVE
INSERT
INT
INTEGER
INTERVAL
INTO
IS
ITERATE
JOIN
KEY
KEYS
KILL
LEADING
LEAVE
LEFT
LIKE
LIMIT
LINES
LOAD
LOCALTIME
LOCALTIMESTAMP
LOCK
LONG
LONGBLOB
LONGTEXT
LOOP
LOW_PRIORITY
MATCH
MEDIUMBLOB
MEDIUMINT
MEDIUMTEXT
MIDDLEINT
MINUTE_MICROSECOND
MINUTE_SECOND
MOD
MODIFIES
NATURAL

NO_WRITE_TO_BINLOG
NOT
NULL
NUMERIC
ON
OPTIMIZE
OPTION
OPTIONALLY
OR
ORDER
OUT
OUTER
OUTFILE
PRECISION
PRIMARY
PROCEDURE
PURGE
READ
READS
REAL
REFERENCES
REGEXP
RENAME
REPEAT
REPLACE
REQUIRE
RESTRICT
RETURN
REVOKE
RIGHT
RLIKE
SCHEMA
SCHEMAS
SECOND_MICROSECOND
SELECT
SENSITIVE
SEPARATOR
SET
SHOW
SMALLINT
SONAME
SPATIAL
SPECIFIC
SQL

SQL_BIG_RESULT
SQL_CALC_FOUND_ROWS
SQL_SMALL_RESULT
SQLEXCEPTION
SQLSTATE
SQLWARNING
SSL
STARTING
STRAIGHT_JOIN
TABLE
TERMINATED
THEN
TINYBLOB
TINYINT
TINYTEXT
TO
TRAILING
TRIGGER
TRUE
UNDO
UNION
UNIQUE
UNLOCK
UNSIGNED
UPDATE
USAGE
USE
USING
UTC_DATE
UTC_TIME
UTC_TIMESTAMP
VALUES
VARBINARY
VARCHAR
VARCHARACTER
VARYING
WHEN
WHERE
WHILE
WITH
WRITE
XOR
YEAR_MONTH
ZEROFILL

PHP API MySQL


PHP API.
(
connect_id), MySQL, ( result_id),
mysql_query(). ,
.
([]).

mysql_affected_rows
mysql_affected_rows() , MySQL-. :
int mysql_affected_rows([resource connect_id]);

, INSERT,
UPDATE, REPLACE DELETE , . DELETE WHERE, ,
.
SELECT ( , ). SELECT, mysql_num_rows().

mysql_close
mysql_close() MySQL-. :
bool mysql_close([resource connect_id]);

188

: true , false .
mysql_close() MySQL, . ,
, . .
.
mysql_close() ,
mysql_pconnect().

mysql_connect
mysql_connect MySQL-.
:
resource mysql_connect([string hostname [, string username
[, string password [, bool new_connect]]]]);

MySQL
false .
mysql_connect() MySQL-.
, ,
'localhost', ,
, . hostname ( "localhost:3306").
mysql_connect()

. new_connect, true,
.
, , mysql_close().
:
<?php
$id_con = mysql_connect("localhost", "mysql_user", "mysql_password")
or die(" ");
print (" ");
mysql_close($id_con);
?>

2. PHP API MySQL

189

mysql_create_db
mysql_create_db() MySQL. :
bool mysql_create_db(string database_name [, resource connect_id]);

mysql_create_db() , .
true false .

mysql_data_seek
mysql_data_seek() .
:
int mysql_data_seek(resource result_id, int row_number);

: true , false
.
mysql_data_seek()
( SELECT , , ).

mysql_db_query
mysql_db_query MySQL-. :
resource mysql_db_query(string database_name, string query
[, resource connect_id]);

MySQL false .
mysql_db_query() .
, mysql_query().

mysql_drop_db
mysql_drop_db() MySQL. :
bool mysql_drop_db(string database_name [, resource connect_id]);

190

: true , false .

mysql_errno
mysql_errno()
MySQL. :
int mysql_errno([resource connect_id]);

mysql_error
mysql_error
MySQL. :
string mysql_error([resource connect_id]);

mysql_escape_string
mysql_escape_string
mysql_query(). :
string mysql_escape_string(string str);

str,
(\).

mysql_fetch_array
mysql_fetch_array() . :
array mysql_fetch_array(resource result_id [, resource result_type]);

false .
mysql_fetch_array()
mysql_fetch_row(). ,



, ,
. , / .
, (alias) .

2. PHP API MySQL

191

result_type :
 MYSQL_ASSOC ;
 MYSQL_NUM ;
 MYSQL_BOTH .

mysql_fetch_assoc
mysql_fetch_assoc() . :
array mysql_fetch_assoc(resource result_id);


false, .

mysql_fetch_field
mysql_fetch_field()
. :
object mysql_fetch_field(resource result_id [, int field_number]);

mysql_fetch_field() . , ,
mysql_fetch_field().
:
 name ;
 table , ;
 max_length ;
 not_null 1, ;
 primary_key 1, ;
 unique_key 1,

( UNIQUE);

 multiple_key 1,

( UNIQUE);
 numeric 1, ;

 blob 1, BLOB;
 type ;

192

 unsigned 1, ;
 zerofill 1, ZEROFILL.

mysql_fetch_lengths
mysql_fetch_lengths
. :
array mysql_fetch_lengths(resource result_id);

( ),
, mysql_fetch_row(), false .

mysql_fetch_object
mysql_fetch_object() . :
object mysql_fetch_object(resource result_id [, resource result_type]);

, , false, .
mysql_fetch_object() mysql_fetch_array() . ,
, ( ).
:
<?php
$id_con=mysql_connect($host,$user,$password);
$result_id = mysql_db_query("database_name","select * from table");
while($row = mysql_fetch_object($result)) {
echo $row->last_name;
echo $row->first_name;
}
mysql_free_result($result_id);
?>

mysql_fetch_row
mysql_fetch_row() . :
array mysql_fetch_row(resource result_id);

2. PHP API MySQL

193

false,
.
mysql_fetch_row()
( ). .
.
mysql_fetch_row() false, .

mysql_field_flags
mysql_field_flags() , .
:
string mysql_fields_flags(resource result_id, int field_number);

,
(. 2.1).
2.1. mysql_field_flags()

auto_increment

auto_increment

binary

binary

blob

Blob Text

enum

Enum

multiple_key

not_null

not_null

primary_key

timestamp

Timestamp

unique_key

unique

unsigned

unsigned

zerofill

zerofill

explode(). field_number () , 0.

194

mysql_field_len
mysql_field_len() . :
int mysql_field_len(resource result_id, int field_number);

. field_number () , 0.

mysql_field_name
mysql_field_name() .
:
string mysql_field_name(resource result_id, int field_number);

mysql_field_name() .
, . .
mysql_field_name($result,2) ,
($result).

mysql_field_seek
mysql_field_seek()
. :
int mysql_field_seek(resource result_id, int field_number);

. mysql_fetch_field() (
), . true, ,
false . field_number () , 0.

mysql_field_table
mysql_field_table() ,
. :
string mysql_field_table(resource result_id, int field_number);

. field_number ()
, 0.

2. PHP API MySQL

195

mysql_field_type
mysql_field_type() .
:
string mysql_field_type(resource result_id, int field_number);

mysql_field_type() mysql_field_name(). , ('int', 'real', 'string', 'blob'


. .).

mysql_free_result
mysql_free_result() . :
int mysql_free_result(resource result_id);

mysql_free_result() , ,
.
.

mysql_list_dbs
mysql_list_dbs() , , . :
resource mysql_list_dbs([resource connect_id]);

mysql_list_fields
mysql_list_fields() . :
resource mysql_list_fields(string db_name, string table_name
[, resource connect_id]);

.
. 1,
.
$phperrmsg, @mysql(), .

196

mysql_list_processes
mysql_list_processes() , , . :
resource mysql_list_processes([, resource connect_id]);

mysql_list_tables
mysql_list_tables() . :
resource mysql_list_tables(string db_name, [, resource connect_id]);

mysql_list_tables() , mysql_db_query(),
.

mysql_num_fields
mysql_num_fields() . :
int mysql_num_fields(resource result_id);

mysql_num_rows
mysql_num_rows() . :
int mysql_num_rows(resource result_id);

mysql_pconnect
mysql_pconnect() MySQL. :
int mysql_pconnect([string hostname [, string username
[, string password]]]);

mysql_pconnect() MySQL-
false
.

2. PHP API MySQL

197

mysql_pconnect() mysql_connect() :


, .
, ( );

 SQL ,

( mysql_close() ,
mysql_pconnect()).

mysql_ping
mysql_ping() .
:
bool mysql_ping([resource connect_id]);

mysql_ping() ,
. , .
true,
, false .

mysql_query
mysql_query() SQL-. :
int mysql_query(string query [, resource connect_id]);

mysql_query() . connect_id ,
. , ( mysql_connect())
.
true false,
UPDATE, INSERT DELETE. ,
. SELECT
.

198

mysql_result
mysql_result() . :
mixed mysql_result(resource result_id, int row, mixed field);

mysql_result()
. field , , _._.
, , .
, , mysql_result().
, field ,
mysql_result() ,
_ _._.
mysql_result()
, .

mysql_select_db
mysql_select_db() MySQL.
:
int mysql_select_db(string db_name [, resource connect_id]);

true false
.
mysql_select_db()
, . , . mysql_query()
.


, :
 string mysql_get_client_info(void)

 string mysql_get_host_info([resource connect_id]) -

2. PHP API MySQL

199

 int mysql_get_proto_info([resource connect_id])

 string mysql_get_server_info([resource connect_id]) -

 string mysql_info()

 string mysql_stat([resource connect_id])

 int mysql_thread_id([resource connect_id]) -

, ;

 string mysql_character_set_name([resource connect_id])



,
.

3
1. MySQL?
: CHAR, VARCHAR, TEXT, BLOB.
2.
SMALLINT?
: 2 .
3. YEAR?
: 1901 2155.
4. MySQL ?
: ISAM, MyISAM, HEAP, BDB, InnoDB, MERGE.
5. ?
: MyISAM.
6. ?
: HEAP.

7
1. ?
: DROP INDEX ALTER
TABLE.

3.

201

2. MySQL?
: MySQL :
 ;
 ;
 FULLTEXT.

8
1. ALTER TABLE ?
: DROP.
2. ?
: FIRST AFTER.

17
1. ( ).
3.1.
3.1. 1
<?php
require "dbconnect.php";
?>
<html>
<head>
<title></title>
</head>
<body>
<table border width="100%">
<tr><td><b> </b></td><td><b> </b>
</td></tr>
<?php
$res_id=mysql_query("select title, count(id_unit) from book, unit where
book.id_book=unit.id_book group by unit.id_book");
while($arr_book=mysql_fetch_row($res_id))
{

202

echo "<tr><td>$arr_book[0]</td><td>$arr_book[1]</td></tr>";
}
?>
</table>
</body>
</html>

2. ()
.
3.2.
3.2. 2
<?php
require "dbconnect.php";
if(isset($_POST['new_section']))
{
$query="insert into section values('','".$_POST['new_section']."')";
if(mysql_query($query))
{
echo " ";
}
else
{
echo mysql_error();
}
}
?>
<html>
<head>
<title> </title>
</head>
<body>
<form method="POST">
<select>
<?php
$res_id=mysql_query("select section from section");
while($arr_auth=mysql_fetch_row($res_id))
{
echo "<option>$arr_auth[0]</option>";
}
?>

3.
</select>
<input type="text" name="new_section">
<input type="submit" name="add" value="">
</form>
</body>
</html>

203

Library

SOFT

data_for_library.txt ;

library.txt CREATE TABLE


;

db_librzry.txt ( dump )

Apache web-
MySQL MySQL
PHP PHP


A, B
AUTHOR_LIST.PHP 170
BETWEEN AND, 121

C, D
Composite primary key 26
CROSS JOIN, 138
DBCONNECT.PHP 169

E
Entity 17
ENUM, 45
Equi-join 138
Escape- 159

F
Foreign key 27
FRM, 51, 54

G, H
GROUP BY, 125
HAVING, 126

I
IGNORE, 101
IN, 120

ISD, 52
ISM, 52

J, L
JOIN, 138
LOAD DATA, 100

M
Michael Stonebreaker 13
MRG, 54
MYD, 53
MYI, 53, 54
MYSQLADMIN.EXE 73
MYSQLD.EXE 68
MYSQLDUMP.EXE 74
MYSQLSHOW.EXE 69, 93

N
Non-transaction-safe tables, NTST 52

P
PHP, 155
PHP.INI 180
Primary key 25

R
Relation 17
Robert Klein 14

206

S
Script 155
SET, 46
Shortcut 71

TEST_LINK.PHP 181
Transaction-safe tables, TST 52

W
Web- 13
WHERE, 135

TEMPORARY, 150

55
15
158
160
23, 24

35, 80
180
40

,
27
150
41
41, 43

94
40
41
61

80, 84
88

82
35
36
80

54
15
21
22
88
, 50
45
:
83
83
81
80
82
42

102
PHP 159
108
170
24
157
132, 161
39, 40, 46
15

159
161
112
112

13
82
PHP 160
82
27
54
46
14

15
52
80
22, 24
24, 28

138
23
118
27
27
79

207

54
17

25, 79, 84
:
88
91
136
45
()
117
141
54
82
:
80
80
88
88
83
80
80
79
88
80
81
88
80
138
99
, 83
39, 40
PHP- 167

42

108
81
38
108
75
174

208

16
14

23
27
15
65, 73
15
155
:
83
79
122
25, 80
159
50
28, 136
53
128
79
23
155

:
88
83
91
79
113
38
, 43
:
79
34
27

71
52
151

:
75
22
84
88
85
15
122

54
:
41
41, 42
, 166

160
- 53

,
80
3840,
46, 51

,
106
24