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

PHP and

MySQL

The book that should have been in the box

Brett McLaughlin

Beijing | Cambridge | Farnham | Kln | Sebastopol | Tokyo

PHP
MySQL

2013

32.988-02-018
004.738.5
15

15 PHP MySQL. . .: , 2013. 512 .: .


ISBN 978-5-459-01550-8
CSS JavaScript,
- - PHP MySQL. .
, ,
, -.
PHP- -.
PHP SQL.
.
-, .
, .
,
.
.

32.988-02-018
004.738.5

'Reilly. .

.
, , ,
. , ,

, .

ISBN 978-0596515867 .

2012 Brett McLaughlin. All rights reserved

ISBN 978-5-459-01550-8

, 2013

, 2013


. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

1. PHP MySQL
1. PHP: , ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2. PHP: . . . . . . . . . . . . . . 50
3. MySQL SQL: . . . . . . . . . . . . . . . . . . . . . . . . . 82

2. -
4. PHP MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
5. . . . . . . 157
6. -. . . . . . . . . . . . . . . . . . . . . . 174

3. - -
7. - ( ) . . . . . . . .
8. . . .
9. . . . . . . . . . . . . . . . .
10. , . . . . . . . . . . .

222
260
294
337

4.
11. . . . . . . . . . . . . . . . . . . . . . . . . . 392
12. Cookie-,
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
13. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469


. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
PHP?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PHP . . . . . . . . . . . . . . . . . . . . . . . . .
PHP , JavaScript. .
PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
MySQL?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Macintosh Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
FTP: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

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

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

14
15
17
17
18
18
19
19
19
20
20
21

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

1. PHP MySQL
1. PHP: , ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
. . . . . . . . . . . . . . . . . . . . .
PHP (PC) . .
PHP Macintosh . . . . . . . . . . . . . .
. . . . . . . . .

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

26
27
32
36

. . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . .
: HTML- . .
PHP-. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . .
HTML, CSS PHP . . . . . . . . . . .
. . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

39
41
42
42
43
45
46
48

2. PHP: . . . . . . . . . . . . . . 50
- . . . . . . . . . . . . . . .
. .
. . . . . . . . . . . . . . . . . .
PHP. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
$_REQUEST . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . .
$_REQUEST . . . . . . . . . . .
?. . . .

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

50
50
54
58
58
60
65
68
73
74
76
80

3. MySQL SQL: . . . . . . . . . . . . . . . . . . . . . . . . . 82
?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . .
. . . . . . .
() . . . . . .
MySQL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
MySQL Windows. . . . . . . . . . . . . . . . . . . . . . . . . . . .
MySQL Mac OS X . . . . . . . . . . . . . . . . . . . . . . . . . . .
SQL-. . . . . . . . . . . . . . . .
SQL . . . . . . . . . . . . . . .
-. . . . . . . . . . . .
USE. .
CREATE. . . . . .
DROP . . . . . . . . .
INSERT. .
SELECT. . . . . . . . . . . . . . . .

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

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

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

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

. . . . . . . 82
. . . . . . . 82
. . . . . . . 84
. . . . . . . 86
. . . . . . . 86
. . . . . . . 88
. . . . . . . 94
. . . . . . 100
. . . . . . 105
. . . . . . .107
. . . . . . 109
. . . . . . 110
. . . . . . 114
. . . . . . 115
. . . . . . 116

2. -
4. PHP MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
PHP-, . . . .
MySQL. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
SHOW. . . .
. . .
SQL-. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
, . . . . .
SQL- . . . . . . . . . . . .
HTML- . . . . . . . . . .
( ). . . . . . . . . . . . . . . . . . . . . . .
SQL- ( ). . . . . . . . . . . . . . .
,
-. . . . . . . . . . . . . . . . . . . . . . . . . .
,
SELECT. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

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

.
.
.
.
.
.
.
.

120
121
125
127
128
129
133
134

.
.
.
.
.
.

135
137
140
140
142
143

. 145
. 148
. 152
. 153

5. . . . . . . 157
, . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
... . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
trim strtoupper. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
: . .

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

158
158
.160
164
166
168
172

6. -. . . . . . . . . . . . . . . . . . . . . . 174
. . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
id. .
. . . . . . . . . . . . . . . . . . . . . . . . . .

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

174
176
177
178

ID . . . . . . . . . . . . . . . . . 178
. . . . . . . . . . . . . . . . . . . . . . 180
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
SQL-. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
. . . . . . . . . . . . . . . . . . . . . . . . . 188
. . . . . . . . . . . . . . 189
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
. . . . . . . . . . . . . . . . 191
ALTER. . . . . . . . . . . . . . . . 194
: . . . . . . . . . . . . . . . . . . . . . . . . . . 196

SELECT. . . . . . . . . . . . . . . . . . . . . . . . . . . 201
SQL-. . . . . . . . . . . . . . . . 204
ID show_user.php. . . . . . . . . . . . 207
,
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
. . . . . . . . . . . . . . . . . . 213

( ). . . . . . . . . . . . . . . . . . . . . . . . . . . . 216

3. -
-
7. - ( ) . . . . . . . . 222
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
?. . . . . . . . . . . . . . . . . . . . . . . . . . . 225
, . . . . . . . . . . . . . . . . . 228
PHP. . . . . . . . . . . . . . . . 230
PHP . . . . . . . . . . . . . . . . . . . . . . 231
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
. . . . . . . . . . . . 237
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
,
PHP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241

10

require require_once. . . . . . . . . . . . . . . . . . . . . . . . . . . . 247


, . . . . . . . . . . . . . . . . . . . . . . . . . 249
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
show_error.php. . . . 251
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
. . . . . . . . . . . . . . . . . . . . . . . . 256

8.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .261
HTML . . . . . . . . . . . . . . . . . . . . . . . . . . 263
. . . . . . . . . . . . . 266
?. . . . . . . . . . . . . . . . . . . . . . . . 270
. . . . . . . . . 279
, . . . . . . . . . . . . . . . . . . . . . . . 282
SELECT
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
URL-. . . . . . . . . . . 285
: . . . . . . . . . . 289
app_config.php. . . . . . . . . . . . . 291
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293

9. . . . . . . . . . . . . . . . . 294
. . . . . . . . . . . . . . . . . . . . . 294
. . . . . . . . . . . . . . . . . . . . . 297
getimagesize . . . . . . . . . . . . . . 300
file_get_contents . . . . . . . . . . . . 300
INSERT. . . . . . . . . . . . . 300
. . . . . . . . . . . . . . . . . . . 301
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
ID . . . . . . . . . . . . . 305
. . . . . . . . . . . . . . . . . . . . . . . . . . 308
. . . . . . . . . . . . . . . . 310
WHERE. . . . . . . . . . . . . . . . . 316
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
, . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328

11

, . . . . . . . . . . 329
. . . . . . . . . . . . . . . . . . 329

(src) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
, ?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .335
, ... . . . 335

10. , . . . . . . . . . . . 337
, . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
,
- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
SELECT ( )
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
. . . . . . . . . . . . . . . . 344
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 351

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
, . . . . . . . . . . . . . . . . . . . . 358
. . . . . . . . . . . . . . . . 359
,
JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
alert . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
. . . . . . . . . . . . . . . . . . . . . . . . . 369
. . . . . . . . . . . . 372
. . . . . . . . . . . 374
View Display . . . . . . . . . . . . 376
, . . . . . . . . . . . . . . . . . . . . . . 377
View. . . . . . . . . . . . . . . . . . 377
. . . . . . . . . . . . . . . . . . . . . . . . . 378

View. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
. . . . . . . . . . . . . . . . . . . 386

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387

12

4.
11. . . . . . . . . . . . . . . . . . . . . . . . . . 392
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
HTTP-. . .
... . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
( !). . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
: authorize.php. . . . . . . . . . . . . . . . . . .
PHP . . . . . . . . . . . . . . . . . . . . . .
users . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
authorize.php users. . . . . . . . . . . .
,
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
crypt. . . . . . . . . . . . . . . . . .
crypt . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .

393
394
395
396
397
398
399
403
403
407
408
409
411
415
.419
422
423
424
425

12. Cookie-,
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. .
HTTP- ookie-. . . . . . . .
cookie-. . . .
?. . . . . . . . . . . . . . . . . . . .
?. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . .
cookie-. . . . . .
. . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .

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

429
430
432
435
436
438
438
440
442
444
447
450
454

13

- . . . .
. . . . . . . . . . . . . . . . .
HTML . . . . . . . . . . . .
. .
cookie- . .

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

455
456
459
463
465

13. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
. . . . . . . . . . . . . . . . . . . . . . . . .
groups . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
authorize.php . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
, , . . . . . . . . . . . . . . . . . . .
, . .
. . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
$_COOKIE $_SESSION. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
$_REQUEST
$_SESSION. . . . . . . . . . . . . . . . . . . . . . . . . . .
?. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
?. . . . . . . . . . . . . . . . . . . . . . . .
cookie-?. . . . . . . . . . . . . . . . . . .

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

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

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

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

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

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

469
470
471
475
476
477
479
481
485
487
491
494
494
495
496

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

500
502
503
504
507


- HTML.
Cascading Style Sheets (CSS)

JavaScript
,

-. ,


JavaScript
,
jQuery
-. JavaScript ,
CSS HTML
.
.
, , -, cookie-. ,
-,
PayPal , .
,
, HTML, CSS JavaScript.
PHP MySQL
.
PHP, , -
-,
. , .

PHP?
PHP . JavaScript ,
,
. HTML ,
, -. , PHP

- : ,
.

15

PHP?
PHP . PHP Personal Home Page
( ), -, HTML, CSS JavaScript. Personal
Home Page , , - , , .
PHP PHP: Hypertext Preprocessor (PHP:
). , ,
: PHP , .
, , .
, , .
, PHP , PHP.

PHP
-,
.
PHP
, ( , .0.1),
PHP .

. 0.1. PHP-
Windows

PHP HTML-, -
cookie-.
.
HTML-,
HTML, , PHP.

16

PHP, HTML, ,
, PHP-:
<?php
require '../../scripts/database_connection.php';
// ,
$user_id = $_REQUEST['user_id'];
// SELECT
$select_query = "SELECT * FROM users WHERE user_id = " . $user_id;
//
$result = mysql_query($select_query);
//
?>
<html>
<!-- HTML PHP -->
</html>

? , HTML

, (.0.2). PHP,
HTML.
. ,
.
HTML
. PHP

: HTML JavaScript
PHP, .

. 0.2. HTML

17

PHP ,
JavaScript
JavaScript, , JavaScript
, .
, , var. , ,
, .
.
PHP , JavaScript,
,
. ,
JavaScript. ,
PHP . ,
, ... ...
.
, . ,
. PHP

, - .
, Internet Explorer, JavaScript.

PHP
PHP- ,
, .
PHP
() -, ,
, - HTML

- .
.
, Java C++,
. ,
, :
, , ,
.
, PHP JavaScript, ,
.
- . PHP. .
. , ,
.

18

MySQL?
MySQL
. , . , MySQL

SQL
( ,
MySQL
) . MySQL 3,
PHP.
,
MySQL
, , . , MySQL
, , , .
() MySQL.
, ,
.


PHP -, , .
( ) -, PHP-.
, ? - . .
- .
,
, PHP.
PHP-,
... ...
-. ,
PHP
,
.
.
,
-, . , HTML CSS
, , JavaScript. -
, ,
. ,
-
.

19

Macintosh Windows
PHP MySQL, Macintosh Windows,
. , -
. ,
-, .
, ,
PHP-. ,
: Macintosh Windows.
. , HTML CSS.

FTP:
,
FTP
-.
PHP
- , vi emacs.

.
, ,
, ,
.

FTP-. , .

1 ,

FTP
-. Cyberduck (www.cyberduck.ch). ,
. ,
FTP-, - .
.


,
.
1. PHP MySQL. PHP, , PHP
, -

20

. MySQL
.
2. -. , -

-.
, ,
, .
, URL-,
, Twitter .. .
3. - -. ,

,
- .
, , , . ,
, ,
, ,
.
4. . -


. ,
( ). cookie- - ,
.
- Missing Manual (www.missingmanuals.com/cds/phpmysqlmm) .


, . , ,
, , , . , ,
, ( ) .
www.missingmanuals.com .

-
-, ,
. www.missingmanuals.com/cds/phpmysqlmm
. . .

21

, ,
-. - -,
.

? ?
?
, ,
,
PHP

, MySQL

- . , www.missingmanuals.com/feedback.


(Brett McLaughlin) ,
- ,
. ,
,
.
, , , , ,
. NASA, . ,
, , PHP
MySQL...


(Nan Barber) , Missing Manual
. . : nanbarber@oreilly.com.
(
Jasmine
Perez

, ,
WFMU, , .
: jperez@oreilly.com.
Nan

Reinhardt
)

(
, .
.
www.nanreinhardt.com.
: reinhardt8@comcast.net.
(Shelley Powers) ,
HTML5 ,
OReilly. . -: www.burningbird.net.
(Steve Suehring) ,
.
( ),
- www.braingia.org.

23

. , ,
, . , , .
, , .
, .
, , ,
. (Brian Sawyer) , ,
.
: ,
. (Nan Barber).
, . , , .
(Shelley Powers)
(Steve Suehring), , .
, .
, ,
. ... PHP.
, , , . - , .
OReilly.
. , , , ,
. , -
- , ,
, , , - . .


,
halickaya@minsk.piter.com ( , ).
!
http://www.piter.com
.

PHP MySQL

1. PHP: , ?
2. PHP:
3. MySQL SQL:

PHP: ,
?

PHP , -
-. , PHP,
PHP, ,
PHP ,
-.
. ,
PHP , ,
2, .
, : ? ,
. PHP ,
-.
.
PHP
, HTML

-.


PHP, .
- - , PHP .
PHP .

PHP
- , ,
, , . ,
PHP-
.
PHP

, , . , .

1. PHP: , ?

27

PHP (PC)
. ,
PHP. :

PHP
.

Macintosh, .
PHP Macintosh .

- - www.php.net.
- PHP

,
PHP
, , PHP-. PHP
Stable Releases (.1.1).

. 1.1. PHP
- www.php.net

, . ( , , .)

PHP
PHP, (.1.2).

28

1. PHP MySQL

- ,
.

. 1.2. - PHP

PHP
Windows Binaries ( Windows). ,
PHP Windows-.
: http://windows.php.net/download (.1.3).
http://windows.php.net/download .
: ,
(Non Thread Safe), , (Thread Safe).
Non Thread Safe ( ),
. (
.)
Installer () .
, Windows, PHP.
, .

1. PHP: , ?

29

. 1.3. , PHP Windows


,
, .
:
, .
,
: ! ! ( )
( ).
1.0, . , 2.2 PHP 1.1
,, - . ,
- PHP,
, .
.

30

1. PHP MySQL

, http://windows.php.
net/download, : .
URL-, www.php.net. ,
Google PHP www.php.net,
, Windows- ,
PHP.

, . Windows ,
Allow (),
Next (), .
,
. C:\Program Files\PHP\,
PHP.
- (.1.4). PHP
,
-, ,
- (Do not setup a web server). , .

. 1.4. -

PHP Windows. : ?
PHP , Windows, 2000. PHP :
(Thread Safe). Mac OS X Unix/Linux-
, , Windows . Windows-

1. PHP: , ?

31

, , , PHP
, .
,
. PHP Windows , PHP- Windows ,
. PHP- , -,
Windows, PHP-,
. PHP
-
PHP,
. ,
(Non Thread Safe). ,
: 10 40%
.
, , PHP , , .
. , ( ,
,
), ,
, ,
, , .
, (.1.5). Windows PHP-,
, ,

. 1.5.

32

1. PHP MySQL

(Extras)
. , .
Next (), .
, Install () , . !
PHP.
PHP , cmd. , ,
, PHP. php
(.1.6).

. 1.6. PHP

,
, PHP .
.

PHP Macintosh
Macintosh, ,
, PHP. , ,
Macintosh, PHP.
, Macintosh- Terminal.
Terminal, ,

PHP. Applications ( Shift+ +A), Utilities, .1.7.
Utilities ,

1. PHP: , ?

33

MacOSX. ,
, .

. 1.7. Utilities , MacOSX

Shift+ +A ,
. ,
, Shift+ +A.


, , Finder .
, .
Shift+ +A , . ,
.
, ,
. , Applications
Utilities ().

34

1. PHP MySQL

, Applications () Terminal.

(.1.8).
Terminal
Macintosh .
PHP ,
.

. 1.8. Terminal

Terminal PHP-
. Terminal, dock-.

Terminal

. (.1.9). ,
Terminal

, - . , , ,
, . ,
.

. 1.9. Terminal

1. PHP: , ?

35

, PHP , php,
, Enter.
- .
,
Control+C, . which php.
which , , , php.
, .1.10. , php
/usr/bin. , , .

. 1.10. which

, php, , !

PHP
, PHP
( php, ) . , Apple Software Update,
PHP. , PHP , Terminal php version.
:
Bretts-MacBook-Pro:~ bdm0509$ php version
PHP 5.3.4 (cli) (built: Dec 15 2010 12:15:07)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies

, PHP, , 5.3.4. (
PHP (PC) .)
PHP, - www.
php.net PHP. ,
Macintosh-, , , unzip tar, - ,
.

36

1. PHP MySQL

, Mac Software Update ,


. .
Software Update (
) , Macintosh-. , .


PHP

. PHP- HTML,
CSS JavaScript. ,
, . HTML
HTML,
CSS
CSS, JavaScript

JS,
PHP
PHP.
PHP ,
. ,
PHP. Windows,
. Macintosh,
TextEdit

. , . ,
, PHP,
.
,
PHP. , Windows NuSphere PhpED
(www.nusphere.com/products/phped.htm) (.1.11).
NuSphere ,
$50 $100,
,
PHP
-, , HTML, CSS PHP.
Macintosh,
BBEdit (www.barebones.com/products/bbedit/index.html) TextMate (www.macromates.
com). Macintosh-
, , PhpED,
Windows: , ,
, HTML

, CSS

, JavaScript

, . BBEdit .1.12. $100.


BBEdit ,

37

1. PHP: , ?

. 1.11. NuSphere PhpED


JavaScript, CSS HTML, PHP.
PHP

PHP. HTML,
, PHP -
.

. 1.12. BBEdit

TextMate .1.13. , BBEdit.


, , , . FTP,
. TextMate $60.

38

1. PHP MySQL

. 1.13. TextMate

:
, PhpED, BBEdit TextMate, , , . ,
, Windows Finder Mac-,
telnet Terminal, FTP-
. :
.

,
dock- Macintosh- Windows. - PHP.
.
.
, , , , . , - .
.
FTP,
,
,
.
, ,
, -
FTP telnet. , ,
TextMate PhpED.

1. PHP: , ?

39

PHP

, , .
, TextEdit. PHP ,
.
: Windows TextEdit Macintosh. PHP,
,
. , - ,
PHP
, ,
.

PHP, Eclipse PHP (www.eclipse.org/projects/


project.php?id=tools.pdt). Eclipse IDE
Java-.
PHP, PHP-.
Eclipse , ,
, .
.


PHP, .
PHP-.
, :
<?php
echo " . , PHP-!\n";
echo " :\n";
$name = trim(fgets(STDIN));
echo "\n, " . $name . ", .\n\n";
?>

,
. .
PHP, HTML JavaScript.

, , TextEdit,
. ,
. PHP- .
, ,
. TextEdit FormatMake Plain Text
( ). , .
, .

40

1. PHP MySQL


PHP
, . ($), (< >,
, HTML) (\).
(.1.14).

. 1.14.

, .
1. PHP- <?php.
2. , echo.
3. , echo.
4. $name.
5. , , , $name.
6. ?>.
,
. , , , , ,
, $name =.
\ns STDIN, . : <?php,
, , ?>.
. sayHello.php.
.php, .
- , , , PHP .

Windows Macintosh, ,
, , TXT.
PHP. Windows ,
sayHello.php, - sayHello.php.txt.

1. PHP: , ?

41

PHP-!



, . , .
TextEdit Mac-, Preferences
(). Preferences ,
, .
Format () , , Plain Text ( ) (.1.15). Windows
,
.

. 1.15. TextEdit Preferences ()


+,


, ? , . PHP. .
Mac-, Terminal , ,
dock-. Terminal .

42

1. PHP MySQL

, sayHello.
php. , ,
dir ( Windows) ls ( Macintosh).
, :
php sayHello.php

php
sayHello.php. ,
. , Enter. , .1.16.

. 1.16.

C PHP . php,
,
.
! ,
PHP.


, PHP? PHP,
, -
,
JavaScript
. , PHP

, , , . PHP-
-, PHP
HTML-, PHP-.

: HTML-
HTML-
HTML-:
<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />

1. PHP: , ?

43

</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"> 1.1</div>
<div id="content">
<h1> !</h1>
<p> . , PHP-!</p>
<p> :</p>
<form action="scripts/sayHelloWeb.php" method="POST">
<p>
<i> :</i> <input type="text" name="name" size="20" />
</p>
<p><input type="submit" value=" " /></p>
</form>
</div>
<div id="footer"></div>
</body>
</html>

, HTML, ,
, - www.missingmanuals.com/cds/phpmysqlmm.
CSS , ,
. (,
PHP), .

.
CSS,
, ,
sayHello.php, ,
.
, ,
:
<form action="scripts/sayHelloWeb.php" method="POST">

, sayHelloWeb.php PHP-, .
sayHelloWeb.php,
.

PHP-
HTML-,
sayHelloWeb.php, .
PHP
- ,

44

1. PHP MySQL

. ,
, - .
.
PHP-
( - HTML
sayHello.php):
<html>
<head>
<link href="../../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"> 1.1</div>
<div id="content">
<h1>, <?php echo $_REQUEST['name']; ?>!</h1>
<p> .
PHP-.</p>
</form>
</div>
<div id="footer"></div>
</body>
</html>

sayHelloWeb.php ,
.
, , , , ,
HTML. sayHello.php, PHP,
. , PHP
- PHP-
-, ,

HTML
. , , , HTML.
, , -
.
, HTML-,
, , , .
.
html head.
body ,
, HTML- sayHello.html.
h1 ,.

1. PHP: , ?

45

<?php PHP.
$_REQUEST, name echo.
PHP- ?>.
HTML- , sayHello.html.

,
PHP
-, , -, HTML ( ), PHP-.
, - ( sayHello.html),
, , .
HTML- $_REQUEST, PHP
.


PHP

, , . .
PHP
. PHP ,
$. , $myHeight myHeight,
$_REQUEST _REQUEST.

PHP- $,
PHP- , $ . ,
$myHeight PHP- , .

. .
$myHeight ( ) 68 ( 681)

68.
PHP
. , :
, .
sayHelloWeb.php ,
, sayHello.html,
PHP- $_REQUEST. PHP ,
, $_REQUEST , name
(). $_REQUEST['name'] , -, name ().
, , phoneNumber
( ), PHP
$_REQUEST['phoneNumber'].
1

68 173. . .

46

1. PHP MySQL

, $_REQUEST,
.
, , PHP, $_REQUEST.

PHP- name (),


, echo, PHP-. HTML-,
.

HTML, CSS PHP


PHP

- , PHP , .
- -
.
-
(HTML, CSS, JavaScript) -.
- www.yellowtagmedia.
com/sayHello.html. -
HTML -, .
PHP . PHP- ,
- HTML CSS.
, , .
, , (/). -,

HTML-. , URL, yellowtagmedia.com/, -


-.
CSS (css/). , CSS.
JavaScript (js/). JavaScript. -

scripts/, , PHP-
(scripts), .
PHP (scripts/). PHP-.

, php/ phpScripts/, - scripts/, .


(ch01/, ch02/ ..). -

, PHP-.
, .
sayHello.html sayHelloWeb.php ch01/
sayHello.html ch01/scripts/sayHelloWeb.php.

1. PHP: , ?

47

, , , , . , CSS, JavaScript PHP- HTML


PHP.

, HTML- PHP-,
. phpMM.css www.missingmanuals.com/cds/phpmysqlmm CSS
.
, -
, .1.17. HTML- PHP-
, ch01/.
phpMM.css , ,
css/, -.

. 1.17. -

48

1. PHP MySQL



HTML
-
CSS
- ,
HTML
- PHP-. ch01/scripts/
sayHelloWeb.php. PHP .
- -,
ch01/sayHello.html. sayHello.html HTML

, , .1.18.

. 1.18. HTML-, PHP-.


HTML- PHP-

, .

sayHelloWeb.php. -, (.1.19). , - . ,
sayHelloWeb.php
, .
,
. , ,
JavaScript. PHP-, ,
.

1. PHP: , ?

49

. 1.19.

, , ,
. ,
, ,
, , ,
. HTML-,
PHP
-, , , .

PHP:


PHP
-, HTML-. .
PHP

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

-
sayHelloWeb.php name -
sayHello.html :
echo $_REQUEST['name'];

, , $_REQUEST PHP-,
-. ,
.


, $_REQUEST,
, ,
( Twitter,
URL- Facebook ):

2. PHP:

51

<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"> 2.1</div>
<div id="content">
<h1> </h1>
<p>, :</p>
<form action="scripts/getFormInfo.php" method="POST">
<fieldset>
<label for="first_name">:</label>
<input type="text" name="first_name" size="20" /><br />
<label for="last_name">:</label>
<input type="text" name="last_name" size="20" /><br />
<label for="email"> :</label>
<input type="text" name="email" size="50" /><br />
<label for="facebook_url">URL- Facebook:</label>
<input type="text" name="facebook_url" size="50" /><br />
<label for="twitter_handle"> Twitter:</label>
<input type="text" name="twitter_handle" size="20" /><br />
</fieldset>
<br />
<fieldset class="center">
<input type="submit" value=" " />
<input type="reset" value=" " />
</fieldset>
</form>
</div>
<div id="footer"></div>
</body>
</html>

, HTML,
.

HTML
HTML
1.
<p> <i>. ,
HTML.

52

1. PHP MySQL

HTML- .
form , ,
: . ,
<i>, , , -
. HTML, CSS.
.
label for.
, ,
, , .
fieldset, : , . , .
HTML , ( HTML) , : (labels),
, , -.
fieldset.
CSS, . - , CSS . HTML, ,
,
5.
. , , ,
CSS . , CSS
HTML-, .2.1.

, HTML
CSS . , . ,
, .
socialEntryForm.html.
, HTML , ch02/.
, CSS,
, css/, , , , HTML-. ,
. 2.1.
, sayHelloWeb.php, $_REQUEST,
name. , .

2. PHP:

53

. 2.1. ,

getFormInfo.php :
<html>
<head>
<link href="../../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"> 2.1</div>
<div id="content">
<p> , :</p>
<p>
: <?php echo $_REQUEST['first_name']; ?><br />
: <?php echo $_REQUEST['last_name']; ?><br />
: <?php echo $_REQUEST['email']; ?><br />
URL- Facebook: <?php echo $_REQUEST['facebook_url']; ?><br />
Twitter: <?php echo $_REQUEST['twitter_handle']; ?><br />
</p>
</div>
<div id="footer"></div>
</body>
</html>

54

1. PHP MySQL

, getFormIn
fo.php, - -. , socialEntryForm.html
action, .

, .
first_name last_name, name sayHelloWeb.
php, $_REQUEST ,

, .
- .
getFormInfo.php (. 2.2).

. 2.2. PHP , - HTML,


PHP-

$_REQUEST
PHP-:
echo $_REQUEST['FORM_INPUT_FIELD_NAME'];


. sayHello.php ( , ).
:
$name = trim(fgets(STDIN));

2. PHP:

55

PHP .
( ,
. ? !)
:
$numberSix = 6;
$thisIsMyName = "Brett";
$carMake = "Honda";

, , getFormInfo.
php. echo
.
.
<?php
$first_name = $_REQUEST['first_name'];
$last_name = $_REQUEST['last_name'];
$email = $_REQUEST['email'];
$facebook_url = $_REQUEST['facebook_url'];
$twitter_handle = $_REQUEST['twitter_handle'];
?>
<html>
<head>
<link href="../../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<!-- HTML- -->
</body>
</html>

, PHP-, <?php
?>, .
PHP HTML PHP
HTML. PHP-, ,
.
PHP-
html head head body. .

, - , , .
- HTML PHP,
HTML.
, HTML- . (

, . .)
, , PHP HTML, , , getFormInfo.
php, . PHP HTML, , ,
20 30 PHP-, HTML.

56

1. PHP MySQL

, , .2.2, . , HTML-,
, , .
.
$_REQUEST PHP

-, HTML

, HTML.
, -.
. $first_name, $last_name .. HTML- getFormInfo.php
echo ,
$_REQUEST . div - "content":
<div id="content">
<p> , :</p>
<p>
: <?php echo $first_name; ?><br />
: <?php echo $last_name; ?><br />
: <?php echo $email; ?><br />
URL- Facebook: <?php echo $facebook_url; ?><br />
Twitter: <?php echo $twitter_handle; ?><br />
</p>
</div>
,

? !
- PHP .
PHP-, :
$x = $_REQUEST['username'];
$y = $_REQUEST['password'];

, , :
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];

, . .
, , ,
, , - ? , -
:
echo " , " . $y;

, - , $x, $y. : $x $y?

2. PHP:

57

, ,
!
, ,
, , - ,
.
socialEntryForm.html .
, ( , . 2.2).
, , .
. ,
.
,


,
, , . PHP- getFormInfo.php
, echo HTML,
.
- ,
. , , . ,
, . ,
,
. , , . (
.)
, , , .
, , ,
PHP-.
:
. , .
, (

58

1. PHP MySQL

), .
getFormInfo.php.
PHP, ,
HTML. ?
, ,
. ,
,
.
? : , , ,
$_REQUEST. . ,
? PHP ,
, , .

PHP
PHP : .
, , ,
- . PHP caterpillar
, - !(gUHa8@m.@.
,
QBert1. PHP

. PHP

,
: (string). ,
, ,
.


, PHP ,
, ,
. , getFormInfo.php ,
:
$first_name = $_REQUEST['first_name'];
$last_name = $_REQUEST['last_name'];
$email = $_REQUEST['email'];
1

Google, QBert,
.

2. PHP:

59

$facebook_url = $_REQUEST['facebook_url'];
$twitter_handle = $_REQUEST['twitter_handle'];

: $first_name $last_name. ,
, ,
. ,
: ,
! , .
,
, . , , , ,
. , my
girl mygirl.
PHP (.). getFormInfo.
php HTML-, :
: <?php echo $first_name; ?><br />
: <?php echo $last_name; ?><br />

:
: <?php echo $first_name . $last_name; ?><br />

socialEntryForm.html, - . .2.3.

. 2.3. , ,
-

60

1. PHP MySQL

! : . .
, PHP .
: " ". PHP ,
- . $first_name, $last_name:
: <?php echo $first_name . " " . $last_name; ?><br />

, . , .2.4
.

. 2.4. PHP , : $_REQUEST, ,


, ;


, .
PHP . PHP
. , ,
$facebook_url. ,
, :
<p>
: <?php echo $first_name . " " . $last_name; ?><br />
: <?php echo $email; ?><br />

2. PHP:

61

<a href="<?php echo $facebook_url; ?>">URL-a Facebook:</a><br />


Twitter: <?php echo $twitter_handle; ?><br />
</p>

URL

- , (.2.5).

. 2.5. URL , ,
, HTML

- URL- facebook.com? , , ,
URL-, facebook.com, ryan.geyer
profile.php?id=699186223. .
,
$facebook_url facebook.com. , , , URL-. ,
http://www.facebook.com.
PHP

. , facebook.com $facebook_url:
$first_name = $_REQUEST['first_name'];
$last_name = $_REQUEST['last_name'];
$email = $_REQUEST['email'];
$facebook_url = $_REQUEST['facebook_url'];
$position = strpos($facebook_url, "facebook.com");
$twitter_handle = $_REQUEST['twitter_handle'];

62

1. PHP MySQL

strpos() ( string

position
( )) , , , , . $position 5,
facebook.com $facebook_url 5.
( , 5, 6, .)
. - .
,
$facebook_url ( $facebook_url facebook.com)
$facebook_url facebook.com. , ,
$position ( false).
strpos() $facebook_url,
.

strpos(), PHP,
: , , ,
false.

$first_name = $_REQUEST['first_name'];
$last_name = $_REQUEST['last_name'];
$email = $_REQUEST['email'];
$facebook_url = $_REQUEST['facebook_url'];
$position = strpos($facebook_url, "facebook.com");
if ($position === false) {
$facebook_url = "http://www.facebook.com/" . $facebook_url;
}
$twitter_handle = $_REQUEST['twitter_handle'];

, , ,
, . ,
.
1. strpos(), , $facebook_url facebook.com. ,
strpos(), $position.
2. $position PHP-
false, if.
if , :
$position false, , { }.
3. , { }, ,
, , true.
, $position === false. ,
$facebook_url http://www.facebook.com,
Facebook.
4. : $position false,
. { } .

2. PHP:

63


, PHP, Java, C Perl,
0.
(PHP ) , . , , Thats weird, T 0, 1.
.
, - URL- Facebook
getFormInfo.php : facebook.com/michael.greenfield.
, ,
URL:
if (strpos($facebook_url,
"facebook.com") > 0) {
$facebook_url =
"http://www.facebook.com/" .
$facebook_url;
}

PHP- : facebook.com $facebook_url, http://www.facebook.com/ $facebook_url.


, $facebook_url
, : http://www.facebook.com/facebook.com/michael.
greenfield. ?
, PHP 0, 1. 0
$facebook_url.
f. 1 a, 2 c .. , $facebook_url facebook.com,
, . strpos() 0, ,

$facebook_url.
( , , ),
, . , ,
, 1 , 0 . ,
.
, ,
- socialEntryForm.html.
Facebook
, URL- facebook.com, , profile.
php?id=100000039185327. .
. -,
PHP-, , .2.5.

64

1. PHP MySQL

( .2.6) .
, profile.php?id=100000039185327 URL- http://www.facebook.com/profile.php?id=100000039185327
(.2.7).

. 2.6. -

. 2.7. URL- ,

2. PHP:

65


, ,
? , , . ,
.
, ,
Twitter
, -. Twitter @,
: @bdmclaughlin. www.twitter.com @ . , , Twitter
@phpGuy, URL- Twitter
http://www.twitter.com/phpGuy.
, Twitter ,
.
1. $twitter_url
http://www.twitter.com/.
2. , Twitter @.
3. @ $twitter_handle , $twitter_url.
4. @ $twitter_handle , @
$twitter_url.
5. Twitter <a> HTML .
, , ,
.
URL-
Twitter :
$twitter_handle = $_REQUEST['twitter_handle'];
$twitter_url = "http://www.twitter.com/";

, -
Twitter
, $twitter_handle, @. strpos():
$twitter_handle = $_REQUEST['twitter_handle'];
$twitter_url = "http://www.twitter.com/";
$position = strpos($twitter_handle, "@");

- @ $twitter_handle. if,
else:
$twitter_handle = $_REQUEST['twitter_handle'];
$twitter_url = "http://www.twitter.com/";

66

1. PHP MySQL

$position = strpos($twitter_handle, "@");


if ($position === false) {
$twitter_url = $twitter_url . $twitter_handle;
} else {
// @ Twitter
}

. @
,
$twitter_url. @ ,
.
, strpos() , , . PHP
: substr(). substr() substring

(), . substr() ,
.
, substr("Hello", 2) "llo".
, "H" 0, "e" 1,
"l" 2. substr() 2,
: "llo".

, PHP-, substr() strpos(),


. , , .
.

Twitter substr() . , @, , , $position. substr() ,


$position, $position + 1.

?
PHP HTML
PHP HTML, .
, getFormInfo.php:
<a href="<?php echo $facebook_url; ?>">
Facebook
</a><br />

, , :
, . , , PHP- .

2. PHP:

67

, PHP
HTML. , . PHP-
<?php ?>. ( , PHP, ?> , ,
.) , PHP - , ,
, .
, PHP ,
a . ,
PHP- .
PHP , . PHP-,
, :
<a href="<?php echo
'http://www.twitter.com/' .
$twitter_handle; ?>">
Facebook
</a><br />


:
<a href='<?php echo
"http://www.twitter.com/" .
$twitter_handle; ?>'>
Facebook
</a><br />

, -

. , .
-, PHP
, .
$twitter_handle = $_REQUEST['twitter_handle'];
$twitter_url = "http://www.twitter.com/";
$position = strpos($twitter_handle, "@");
if ($position === false) {
$twitter_url = $twitter_url . $twitter_handle;
} else {
$twitter_url = $twitter_url . substr($twitter_handle, $position + 1);
}

, ,
- . . .

68

1. PHP MySQL

, HTML:
<p>
: <?php echo $first_name . " " . $last_name; ?><br />
: <?php echo $email; ?><br />
<a href="<?php echo $facebook_url; ?>">URL- Facebook</a><br />
<a href="<?php echo $twitter_url; ?>"> Twitter</a><br />
</p>

, ,
. @ Twitter .
:
Facebook Twitter @ (.2.8).

. 2.8.

PHP

. ,
: Twitter. ,
PHP-, .



PHP

, . , -, ,
URL-:
, http://www.facebook.
com/ryan.geyer http://www.facebook.com/ryan.geyer ;

2. PHP:

69

com org URL-, http://www.


facebook.com/profile.php?id=534643138 http://www.facebook.org/
profile.php?id=534643138.

, com org. ,
_.com, _.org
_.org _.com -
.

, PHP

, PHP-, , ,
.

trim()
PHP- trim() , ,
PHP . I love my space
bar. I love my space bar..

PHP rtrim(), ,
( ), ltrim(), ( ).

, , :
$first_name = trim($_REQUEST['first_name']);
$last_name = trim($_REQUEST['last_name']);
$email = trim($_REQUEST['email']);
$facebook_url = trim($_REQUEST['facebook_url']);
$position = strpos($facebook_url, "facebook.com");
if ($position === false) {
$facebook_url = "http://www.facebook.com/" . $facebook_url;
}
$twitter_handle = trim($_REQUEST['twitter_handle']);
$twitter_url = "http://www.twitter.com/";
$position = strpos($twitter_handle, "@");
if ($position === false) {
$twitter_url = $twitter_url . $twitter_handle;
} else {
$twitter_url = $twitter_url . substr($twitter_handle, $position + 1);
}

:
$_REQUEST trim().

70

1. PHP MySQL

trim() (, rtrim() ltrim()) ,


. trim()
, , . ,
, ,
.


str_replace()
. str_
replace(), .
. facebook.org, "facebook.
org".
. facebook.org facebook.com,
"facebook.com".
, . ,

-.

( !)
, , PHP
. PHP-:
$facebook_url =
str_replace(
"facebook.org",
"facebook.com",
trim($_REQUEST['facebook_url']));

.
, :
$facebook_url = $_REQUEST['facebook_url'];
$facebook_url = trim($facebook_url);
$facebook_url =
str_replace(
"facebook.org", "facebook.com",
$facebook_url);

, . ,
. ?
. , : - ,
, ? ,

2. PHP:

71

.
, .
, .
, - , . ,
,
.
, - .
. ,
, .
,
( ) .
, ,
. , getFormInfo.php , .
6, 7 10,
.
,
:
$facebook_url = str_replace("facebook.org", "facebook.com",
trim($_REQUEST['facebook_url']));
$position = strpos($facebook_url, "facebook.com");
if ($position === false) {
$facebook_url = "http://www.facebook.com/" . $facebook_url;
}

, str_replace() ,
.

, -. ,
PHP
-, URL- facebook.org, , .2.9.
, , .2.10, , getFormInfo.php .
URL-.
View Source ( ).
. ,

72

1. PHP MySQL

. 2.9.

. 2.10.

. ,
. , , (.2.11).

2. PHP:

73

. 2.11. View Source ( )

$_REQUEST
PHP ,
. ,
,
PHP
-. , , , , .
, . , . : , .

PHP
, PHP . www.php.net/manual/en/ref.strings.
php, , PHP.
. : . PHP www.php.net/manual , . ,
, PHP
. . (, , ,
PHP , .
.)

74

1. PHP MySQL

, PHP, PHP. ,
, ,
.
.
PHP, , .


. ,
, , .
. , , .
, , , $file_cabinet
, , .
$file_cabinet URL-, ,
..
PHP ,
, , :
<?php
$file_cabinet[0]
$file_cabinet[1]
$file_cabinet[2]
$file_cabinet[3]
$file_cabinet[4]

=
=
=
=
=

"Derek";
"Trucks";
"derek@DerekTrucks.com";
"http://www.facebook.com/DerekTrucks";
"@derekandsusan";

?>

, ,
- , .

, , ( PHP) php.

.

$file_cabinet ,
:
$first_name = $file_cabinet[0];
$last_name = $file_cabinet[1];
$email = $file_cabinet[2];
$facebook_url = $file_cabinet[3];
$twitter_handle = $file_cabinet[4];

2. PHP:

75

, , , PHP
(. .
). .
$file_cabinet $file_cabinet[0], $file_cabinet[1].

, ,
. , , ,
, . , , :
<?php
$file_cabinet[0]
$file_cabinet[1]
$file_cabinet[2]
$file_cabinet[3]
$file_cabinet[4]

=
=
=
=
=

"Derek";
"Trucks";
"derek@DerekTrucks.com";
"http://www.facebook.com/DerekTrucks";
"@derekandsusan";

$first_name = $file_cabinet[0];
$last_name = $file_cabinet[1];
$email = $file_cabinet[2];
$facebook_url = $file_cabinet[3];
$twitter_handle = $file_cabinet[4];
echo
echo
echo
echo
?>

$first_name . " " . $last_name;


"\n : " . $email;
"\nURL- Facebook: " . $facebook_url;
"\n Twitter: " . $twitter_url;

. - ,
, ?
. - , 2
, 4 URL- Facebook?
.
, , PHP, .
PHP , ,
. ,
, , .
.
, ,
. ,
:
<?php
$file_cabinet['first_name'] = "Derek";$file_cabinet['last_name'] = "Trucks";
$file_cabinet['email'] = "derek@DerekTrucks.com";

76

1. PHP MySQL

$file_cabinet['facebook_url'] = "http://www.facebook.com/DerekTrucks";
$file_cabinet['twitter_handle'] = "@derekandsusan";
$first_name = $file_cabinet['first_name'];
$last_name = $file_cabinet['last_name'];
$email = $file_cabinet['email'];
$facebook_url = $file_cabinet['facebook_url'];
$twitter_handle = $file_cabinet['twitter_handle'];
echo
echo
echo
echo

$first_name . " " . $last_name;


"\n : " . $email;
"\nURL- Facebook: " . $facebook_url;
"\n Twitter: " . $twitter_url;

?>

$file_cabinet .
...

$_REQUEST
PHP, -,
$_REQUEST. .
$_REQUEST['first_name'],
.
( -) ,
. ,
, , ,
PHP-.
, ,
, .
$file_cabinet['first_name'] $file_cabinet[0]. $_REQUEST, . ,
$_REQUEST[0] PHP .
, $_REQUEST? ,
:
<html>
<head>
<link href="../../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"> 2.2</div>
<div id="content">

2. PHP:

77

<p> , $_REQUEST:</p>
<?php
foreach($_REQUEST as $value) {
echo "<p>" . $value . "</p>";
}
?>
</div>
<div id="footer"></div>
</body>
</html>

, ,
. , ,
foreach ( ).
, PHP:
foreach($_REQUEST as $value) {
foreach PHP ,
. foreach $_REQUEST, . ,
, $value. $value, foreach.
foreach $value, .
if, ,
{} PHP , :
foreach($_REQUEST as $value) {
echo "<p>" . $value . "</p>";
}

, {}, . , , $_REQUEST,
:
echo "<p>" . $value . "</p>";

: $value
HTML-.
$value , $_REQUEST,
, $_REQUEST.
, $_REQUEST Derek, Trucks
@DerekAndSusan. PHP ,
:
echo "<p>" . "Derek" . "</p>";
echo "<p>" . "Trucks" . "</p>";
echo "<p>" . "@DerekAndSusan" . "</p>";

78

1. PHP MySQL

showRequestInfo.php.
, - socialEntryForm.php
:
<form action="scripts/showRequestInfo.php" method="POST">
<fieldset>
<label for="first_name">:</label>
<input type="text" name="first_name" size="20" /><br />
<label for="last_name">:</label>
<input type="text" name="last_name" size="20" /><br />
<label for="email"> :</label>
<input type="text" name="email" size="50" /><br />
<label for="facebook_url">URL- Facebook:</label>
<input type="text" name="facebook_url" size="50" /><br />
<label for="twitter_handle"> Twitter:</label>
<input type="text" name="twitter_handle" size="20" /><br />
</fieldset>
<br />
<fieldset class="center">
<input type="submit" value=" " />
<input type="reset" value=" " />
</fieldset>
</form>

socialEntryForm.html - -,
socialEntryForm-2.html enterInformation.html.
: , showRequestInfo.php, ,
getFormInfo.php.

-, .
-:
showRequestInfo.php. ,
- - (.2.12).
, , ?
, .
, , ,
. .
, first_name, last_name, email
.. , , PHP

, . :
$value = $file_cabinet[$key];

, ,
$key. $key first_name, ,
, :
$value = $file_cabinet['first_name'];

2. PHP:

79

. 2.12. -:

showRequestInfo.php
, $_REQUEST. , . , PHP foreach :
<div id="content">
<p> , $_REQUEST:</p>
<?php
foreach($_REQUEST as $key => $value) {
echo "<p> " . $key . ", '" . $value . "'.</p>";
}
?>
</div>

foreach $key $value. => PHP,


$key, $value, . , , , ,
.
PHP (.2.13). ,
: __utmz,
__utma __utmc. -: first_name,
last_name ..

80

1. PHP MySQL

. 2.13. PHP

, $_REQUEST: __utmz
__utmc, - -. HTTP, . .

?
, . - socialEntryForm.html
, , , ( !) . , , . , ,
getFormInfo.php: ! .
PHP

- .
PHP
- , .
PHP- ,
PHP
- : . , ,
, , , .

2. PHP:

81

: ? , , ? , .
-. , ,
.

. ,
.
: ! -,
, ,
. , , :
.

, - . . ,
- .

, , .
? .
.

MySQL SQL:

, : ?
? ? ?
? ,
, -
: ?
-,
- PHP, : . ,
, , , . , ,
. PHP-, .

?
, ,
.

. , ,
.



, PHP

(.
$_REQUEST 2). ?
,
. PHP
. .
.

3. MySQL SQL:

83

.
- ,
-. , , ! ,
, ? ,
.
.
.
, -
,
. ( , ,
.)



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

. , , .
,
. , , .

84

1. PHP MySQL

- : ,
.
. , , ,
, ,
.
.
.
,
, . PHP
? , ,
. ? , .
, .

PHP , 4.


, .
- , -
?
, .
, .
, ,
. ? -
, , - , .
. Mac OS X Spotlight (.3.1) -
QuickSilver (http://quicksilver.en.softonic.com/mac).
Spotlight
Mac

OS

, ,
, . , Spotlight
.
Windows Desktop Search Google (www.google.
com/quicksearchbox) (.3.2). Google Desktop Search Windows,
Macintosh.
, Google Documents Gmail.

.
.

3. MySQL SQL:

85

. 3.1. Spotlight

. 3.2. Google Desktop Search

,
: . -

86

1. PHP MySQL

Spotlight
Google

Search
, , - .
, .

()

, , . . , ,
. .
. ,
, .
, , , , . , ..

. ,
. MySQL , ,
( , - relation),
: . ( , PHP,
.
.)
, , ,
, , .
,
, .
,
.

MySQL
, .
, MySQL,
, -. ,
.

3. MySQL SQL:

87

, .
, Oracle.
, , MySQL:

, , MySQL.
. , ,
MySQL, . ,
, Oracle ( IBM, PostgreSQL
- ), PHP
, MySQL, .


- , , :
. RDBMS (Relational
Database Management Systems, ),
RDBMS-.
. RDBMS, ,
.
.
- (Object-Oriented
Database Management Systems, OODBMS). OODBMS 70-
, 10.
RDBMS , . ,
,
. , RDBMS,
, PHP-
. , , ,
$_REQUEST['first_name'] Users, first_name. ,
.
OODBMS , .
User ,
$_REQUEST['first_name']. ,
, OODBMS User .
, , ,
, .
, OODBMS
, RDBMS, OODBMS
. RDBMS, MySQL,
-, OODBMS,
.

88

1. PHP MySQL

MySQL Windows
MySQL Windows .
: Windows : 32- 64-.
, ,
, . (.3.3).

. 3.3.

Macintosh, .

.
32- , 64- .
, , . , .3.3 32- ,
Windows

7
Professional
. , , Windows, ,
. MySQL 32-,
64- .
- mysql.com (.3.4).
MySQL, ,

3. MySQL SQL:

89

. MySQL
, .
- , MySQL
.
- mysql.com: .

. 3.4. , MySQL

Downloads (GA) ().


MySQL.
MySQL Community Server, Download ()
. , Windows,
(.3.5). ,
MSI Installer, . Zip
archive . , , MSI : 32-bit 64-bit. - MySQL.
. , MySQL ,
.
,
MySQL. , (.3.6),
- , .

90

1. PHP MySQL

. 3.5. MySQL

. 3.6. MySQL

,
mysql-5.5.13-win32.exe. ,
. , . Typical ().
, .

3. MySQL SQL:

91

MySQL Server Instance Configuration


Wizard
.
MySQL
. , . :
.
,
MySQL .

(Standard Configuration) (.3.7). MySQL
Windows,
Windows MySQL .
Launch the MySQL Server automatically ( MySQL-), MySQL
. MySQL- bin
Windows (Include Bin Directory in Windows PATH) (.3.8).
MySQL .
,
MySQL
, , .
, bin MySQL
(PATH).

. 3.7.

(Root Password), , ,
. ,
www.amazon.com www.zappos.com,
22- ,

92

1. PHP MySQL

. 3.8. MySQL

. MySQL ,
- , myqsl_root. ,
MySQL . Execute
(), .

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

MySQL

. , , MySQL Command Line Client (.3.9). MySQL Command Line Client


, mysql.
, , ,
MySQL- bin Windows- PATH MySQL (..3.8).
MySQL Command Line Client .
. ,
:
MySQL. MySQL, ,
PHP,
.

3. MySQL SQL:

93

. 3.9. MySQL Command Line Client

, ,
.3.10.

. 3.10. MySQL Command Line Client

94

1. PHP MySQL

MySQL, ,
.

MySQL Mac OS X

MySQL

Mac

OS

X

Windows
. - www.mysql.com Downloads (GA) () . MySQL Community Server. , MacOSX,
.

Windows, MySQL Windows.

Windows, MySQL Macintosh


. , MySQL, Compressed TAR Archive,
MySQL.
MySQL, .

DMG. MySQL
, .
, : 32- 64-. .
About This Mac ( Mac),
More Info ( ), , .3.11. Processor Name ( ).

. 3.11.

95

3. MySQL SQL:

Macintosh (32 64 )
. , 32-, 64-. ,
. Macintosh
32-, 64-. .3.1 .
3.1. Macintosh

Intel Core Solo

32

Intel Core Duo

32

Intel Core 2 Duo

64

Intel Quad-Core Xeon

64

Dual-Core Intel Xeon

64

Quad-Core Intel Xeon

64

Core i3

64

Core i5

64

Core i7

64

Apple Macintosh.
.3.1, - http://support.apple.com/kb/HT3696.
.

DMG-, .
( ), ,
, .
DMG- .
(.3.12). DMG-
, , .
MySQL
(
), ReadMe.txt.

. 3.12. DMG- MySQL

96

1. PHP MySQL

, mysql5.5.13-osx10.6-x86_64.pkg. .
.
,
.

, , , ,
. Macintosh, ,
. ,
, PHP MySQL.

MySQL , .
,
Macintosh

, . (.3.13).
, . DMG

(.. 3.12). , , .

. 3.13. MySQL

(
Preferences

Pane
) (.3.14). ,

3. MySQL SQL:

97

.
.

. 3.14. MySQL Mac OS X

MySQL (Automatically Start MySQL


Server on Startup), . ,
MySQL, .
, , Macintosh. ( Applications
UtilitiesTerminal (); Terminal , ).
Terminal :
$ /usr/local/mysql/bin/mysql

, . ,

MySQL. ( , MySQL
-, . ,
mysql; .
.)

MySQL (.3.15). Macintosh ,
, . ,
MySQL


PHP
, , , MySQL,
.

98

1. PHP MySQL

. 3.15. MySQL Macintosh

, MySQL
, MySQL Macintosh , Preferences Pane,
mysql Terminal. , .
Terminal
PATH. ( ,
PHP), , ,
. mysql, PATH /usr/local/mysql/bin, ,
mysql . !
, PATH ?
PATH, , . Terminal :
$ defaults write com.apple.finder AppleShowAllFiles TRUE
$ killall Finder

Finder,
Macintosh, , , . Finder,
. Finder .
(.3.16).
, , .

3. MySQL SQL:

99

, . ,
, ,
. , git, , .gitconfig,
DropBox, ,
.dropbox.

. 3.16.

, .profile. , TextEdit, MacOSX.


PATH, ,
. TextEdit .
:
MYSQL_HOME=/usr/local/mysql
export PATH=$MYSQL_HOME/bin:$PATH

, .
.profile,
.
MYSQL_HOME, , MySQL. , MySQL, , , $facebook_url PHP-

100

1. PHP MySQL

(. str_replace() 2).
PATH , bin,
MYSQL_HOME. export MacOSX
PATH .
. ,
, (.), ,
. ( , Finder.)
,
.profile. , .
Terminal mysql. MySQL.
, , Finder
:
$ defaults write com.apple.finder AppleShowAllFiles TRUE
$ killall Finder

,
.
, .3.15, ,
MySQL .

SQL-
, MySQL . MacOSX
Preferences Pane ( .3.14),
Windows , , . , MySQL, ,
(.3.17).

-, MySQL, , ,
.

MySQL :
show databases;

,
. MySQL PHP.

3. MySQL SQL:

101

. 3.17. MySQL


MySQL
, :
mysql> show databases;
+--------------------+
| Database
|
+--------------------+
| information_schema |
| development
|
| eiat_testbed
|
| mysql
|
| nagios
|
| ops_dashboard
|
| performance_schema |
| test
|
+--------------------+
8 rows in set (0.25 sec)


. , : MySQL

, .
show?
: , , databases. MySQL
, .

102

1. PHP MySQL

- : MySQL
, ,
. show databases; 8. , 8 , . , MySQL.
MySQL, mysql,
, MySQL

. use:
use mysql;

mysql. ,
MySQL mysql.
MySQL

, :
show tables;

:
mysql> show tables;
+---------------------------+
| Tables_in_mysql
|
+---------------------------+
| columns_priv
|
| db
|
| event
|
| func
|
| general_log
|
| help_category
|
| help_keyword
|
| help_relation
|
| help_topic
|
| host
|
| ndb_binlog_index
|
| plugin
|
| proc
|
| procs_priv
|
| proxies_priv
|
| servers
|
| slow_log
|
| tables_priv
|
| time_zone
|
| time_zone_leap_second
|
| time_zone_name
|
| time_zone_transition
|
| time_zone_transition_type |
| user
|
+---------------------------+
24 rows in set (0.00 sec)

,
, MySQL.

3. MySQL SQL:

103


mysql.
, . user.
MySQL :
mysql> select * from user;

select : .
(*) : . from MySQL,
: user,
.
,
. - (.3.18). MySQL PHP,
.

. 3.18. select

104

1. PHP MySQL


MySQL
. ,
MySQL


PHP
, .
, , . ,
MySQL user,
. ,
,
.
,
. * , :
mysql> select Host, User, Password from user;

:
mysql> select Host, User, Password from user;
+------------------------+-------+------------------------------------------+
| Host
| User | Password
|
+------------------------+-------+------------------------------------------+
| localhost
| root | *62425DC34224DAABF6995B46CDCC63D92B03D7E9
|
+------------------------+-------+------------------------------------------+
1 row in set (0.00 sec)

, (localhost) root. , , , MySQL


. , .
, ? . , , ,
first_name last_name.

. PHP-
, MySQL .
MySQL .

,
MySQL
, -, .

3. MySQL SQL:

105

SQL

, MySQL
SQL
(Structured Query Language). SQL-:
mysql> select * from user;
...
mysql> select Host, User, Password from user;
...


SQL
-,
SQL
. SQL
, . ,
. , SQL

, . , ,
, :
mysql> select
from
where
and

User, Password
users
first_name = 'Dirk'
country = 'Germany';

where, : users User Password


, (first_name) Dirk, (country)
Germany.

MySQL ?
, PHP,
-.
, jino.ru,
, ,
, ,
-. - .
( ),
PHP MySQL ? ,
PHP-, , PHP (
MySQL) . telnet ssh,
, - .

106

1. PHP MySQL

,
.
-, , .
, -
, MacBook
Pro. , PHP MySQL,
,
.
-, , ,
- ( ).
, , .
, .
, ,
,

. ,
.
, -, ,
. ,
, . - , , ,
Windows, MySQL ,
Mac OS X, .
,
.
, , , -. , ,
-. ,
.

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

SQL ,
. ,
PHP-.

3. MySQL SQL:

107

-

MySQL
, , -. - , ,
, telnet ssh.

telnet ssh, Google


, .
, .
- ssh,
. ,
.


MySQL mysql. -, PHP,
MySQL, ,
mysql.
, ,
:
bmclaugh@akila:~$ mysql
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/
mysql.sock' (2)

, MySQL
. -,
: -
MySQL , , ,
, http://mysql.kattare.com. , MySQL,
, .

mysql ,
mysql hostname=localhost. MySQL
localhost, , .
MySQL, . ,
mysql .

, MySQL

. mysql , , . --hostname= mysql MySQL,

108

1. PHP MySQL

--user= mysql .

MySQL, ,
admin root. ,
telnet ssh. ,
, ,
-. :
, , -.

, :
bmclaugh@akila:~$ mysql --host=dc2-mysql-02.kattare.com
--user=bmclaugh --password
Enter password:

--password MySQL .
, --password=__,

MySQL-.
MySQL,
.3.19.
- SQL.

. 3.19. MySQL

3. MySQL SQL:

109


USE
MySQL, , ,
MySQL, . , ,
SQL-:
myqsl> show databases;

. ,
:
myqsl> show databases;
+----------+
| Database |
+----------+
| bmclaugh |
+----------+
1 row in set (0.09 sec)

,
-. , , mysql
user. , , , ,
. , ljuber,
ljuber, db-ljuber - .
, .

MySQL
, , :
mysql> use bmclaugh;
Database changed

MySQL
. ,
MySQL- use [___].

MySQL. SQL-
. , , :
mysql> SELECT * FROM user;
...
mysql> SELECT Host, User, Password FROM user;
...

110
mysql> SELECT
FROM
WHERE
AND

1. PHP MySQL

User, Password
users
first_name = 'Dirk'
country = 'Germany';

SELECT, FROM, WHERE AND . , , MySQL


, .

MySQL, SELECT
WHERE, ,
.

.


CREATE
mysql USE
, SELECT, users.
, . , SELECT,
- .
,
SQL CREATE. , . ,
.
MySQL :
CREATE TABLE users (

. Enter,
:
mysql> CREATE TABLE users (
->

? , MySQL
. . MySQL

: , . ,
SQL
, Enter. , MySQL

3. MySQL SQL:

111

- . (->) , MySQL .
:
mysql>
->
->
->
->
->
->
->

CREATE TABLE users (


user_id int,
first_name varchar(20),
last_name varchar(30),
email varchar(50),
facebook_url varchar(100),
twitter_handle varchar(20)
);

Enter :
mysql> CREATE TABLE users (
-> user_id int,
-> first_name varchar(20),
-> last_name varchar(30),
-> email varchar(50),
-> facebook_url varchar(100),
-> twitter_handle varchar(20)
-> );
Query OK, 0 rows affected (0.18 sec)

: , .
, , CREATE.
CREATE MySQL, -

.
TABLE MySQL, .

.
users .
( MySQL ,

.
, user_id, , int
varchar(20).

), MySQL ,

.
, , . int,
integer ( ), 1, 890 239402 int, 1,293 3,1456 .

112

1. PHP MySQL

MySQL int, integer. MySQL


.

, varchar, .
varchar (variable character),
() . ,
varchar(20) 1 20.
,
MySQL
, int (user_id), varchar .
, CREATE ?
SHOW:
mysql> SHOW tables;
+------------------------------------+
| Tables_in_bmclaugh
|
+------------------------------------+
| users
|
+------------------------------------+
1 row in set (0.06 sec)

?
PHP MySQL . ,
, MySQL
. MySQL
:
mysql> use
ERROR:
USE must be followed by a database name
mysql>

. , , Enter:
mysql> SELECT *,
->
FROM
->
->

SELECT * . MySQL
Enter
->.
, MySQL SQL.
, ,
.

3. MySQL SQL:

113

, (;),
Enter. , , MySQL .
, , .
.
, . ?
, : DESCRIBE ().
users:
mysql> DESCRIBE users;
+----------------+--------------+------+-----+---------+-------+
| Field
| Type
| Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+-------+
| user_id
| int(11)
| YES |
| NULL
|
|
| first_name
| varchar(20) | YES |
| NULL
|
|
| last_name
| varchar(30) | YES |
| NULL
|
|
| email
| varchar(50) | YES |
| NULL
|
|
| facebook_url
| varchar(100) | YES |
| NULL
|
|
| twitter_handle | varchar(20) | YES |
| NULL
|
|
+----------------+--------------+------+-----+---------+-------+
6 rows in set (0.04 sec)

DESCRIBE DESC ( desc). DESCRIBE users;


SQL.

, MySQL ,
: users ,
.
.


,
, ,
varchar. ,
10 20 varchar(100), .
.
, . , .
, .

114

1. PHP MySQL

, , , URL- Facebook.
15 ( !). , www.facebook.com 20
.
.

. , ,
-
,
varchar .
, , , .
, .
varchar , ,
. ,
.


DROP
, MySQL


SQL
, . , .
delete (), DROP.
, , users
CREATE, users SQL-:
mysql> DROP TABLE users;
Query OK, 0 rows affected (0.10 sec)

!
mysql> SHOW tables;
+------------------------------------+
| Tables_in_bmclaugh
|
+------------------------------------+
0 rows in set (0.06 sec)

. ...
SELECT.
. MySQL

CREATE users.

3. MySQL SQL:

115


. , . .


INSERT
, users.
, . INSERT .

:
mysql> INSERT INTO users
-> VALUES (1, "Mike", "Greenfield", "mike@greenfieldguitars.com",
-> "http://www.facebook.com/profile.php?id=699186223",
-> "@greenfieldguitars");
Query OK, 1 row affected (0.00 sec)

! SQL ,
. users, .
. DESCRIBE:
mysql> DESCRIBE users;
+----------------+--------------+------+-----+---------+-------+
| Field
| Type
| Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+-------+
| user_id
| int(11)
| YES |
| NULL
|
|
| first_name
| varchar(20) | YES |
| NULL
|
|
| last_name
| varchar(30) | YES |
| NULL
|
|
| email
| varchar(50) | YES |
| NULL
|
|
| facebook_url
| varchar(100) | YES |
| NULL
|
|
| twitter_handle | varchar(20) | YES |
| NULL
|
|
+----------------+--------------+------+-----+---------+-------+
6 rows in set (0.29 sec)

, 1, user_id; , "Mike",
first_name ..

, , :
. INSERT, ,
INSERT PHP-.

116

1. PHP MySQL

SELECT
,
SELECT. - ,
SELECT * FROM user
DROP, CREATE INSERT, . ,
:
mysql> SELECT * FROM users;
+---------+------------+------------+----------------------------+-------------------------------------------------+-------------------+
| user_Id | first_name | last_name | email
|
facebook_url
| twitter_handle
|
+---------+------------+------------+----------------------------+-------------------------------------------------+-------------------+
|
1 | Mike
| Greenfield | mike@greenfieldguitars.com |
http://www.facebook.com/profile.php?id=699186223 | @greenfieldguitars
|
+---------+------------+------------+----------------------------+-------------------------------------------------+-------------------+
1 row in set (0.00 sec)

, , . ( SQL- MySQL),
. .
. ,
:
mysql> SELECT first_name, last_name, twitter_handle FROM users;
+------------+------------+--------------------+
| first_name | last_name | twitter_handle
|
+------------+------------+--------------------+
| Mike
| Greenfield | @greenfieldguitars |
+------------+------------+--------------------+
1 row in set (0.00 sec)

.
MySQL
PHP, . PHP

- . , .

SELECT.
, WHERE:

3. MySQL SQL:

117

mysql> SELECT facebook_url


->
FROM users
-> WHERE first_name = 'Mike';
+--------------------------------------------------+
| facebook_url
|
+--------------------------------------------------+
| http://www.facebook.com/profile.php?id=699186223 |
+--------------------------------------------------+
1 row in set (0.00 sec)

WHERE, . , , , SQL.

SQL MySQL?
, SQL MySQL.
, SQL MySQL. , ,
SQL
MySQL.
SQL . MySQL , PostgreSQL Oracle.
, SQL
. , SQL ,
. , SQL
, .
MySQL .
,
SQL. ,
SQL,
SQL. MySQL
SQL (
).
SQL MySQL, . , PHP
MySQL, SQL.
, SQL- ,
SQL. SQL , MySQL. , PostgreSQL
Oracle, .

118

1. PHP MySQL

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

4. PHP MySQL
5.
6. -

PHP
MySQL

,
PHP
MySQL

, .
,
,
. PHP
, MySQL
, php.
PHP , ,
.
,
. , SQL-
MySQL
. ,
PHP
, mysql.
PHP MySQL
. ,
, ,
.

PHP-,

, ,
, .
1. MySQL.
2. USE MySQL.
3. SQL .
4. .
5. .

4. PHP MySQL

121

3, 4 5
. , , ,
.
MySQL
, .

MySQL
PHP-,
. , , PHP, ,
, MySQL.
- , , ,
:
bmclaugh@akila:~$ mysql --host=dc2-mysql-02.kattare.com
--user=bmclaugh --password

, PHP
: , .
,
connect.php. ,
, USE
SQL-, ,
.
:
<?php
mysql_connect("___",
"__", "_")
or die("<p> : " .
mysql_error() . "</p>");
echo "<p> MySQL!</p>";
?>

, PHP
, - , , localhost,
.

! , , , , .
: mysql_connect.
, .
, mysql .

122

2. -

.._, -_ -
.

,
die? ( die
). : die , - . die
: , - ,
. die , .
die,
mysql_connect.
mysql_connect, , . PHP-
PHP MySQL,
. mysql_connect ,
, mysql_connect : false.
,
:
<?php
// ,
if (____mysql_(".._",
"-_", "-")
_______();
else
_____die
?>

, PHP
:
<?php
mysql_connect(".._",
"-_", "-")
or die("<p> : " .
mysql_error() . "</p>");
echo "<p> MySQL!</p>";

?>

,
. , , ( mysql_connect), true
( or), ,die. die , . ,
. , mysql_connect false die, .

4. PHP MySQL

123

MySQL!,
. , ,
. ( die . -
.)
. mysql_connect
. ,
, mysql_error. , mysql_error die,
, .

mysql_connect, mysql_error die .


,
, .
, ,
.
. PHP. , ,
.

mysql_connect ,
. PHP die,
:
echo "<p> MySQL!</p>";

, HTML-
connect.html.
HTML:
<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"> 4.1</div>
<div id="content">
<h1> SQL</h1>
<form action="scripts/connect.php" method="POST">
<fieldset class="center">
<input type="submit" value=" MySQL" />
</fieldset>
</form>
</div>
<div id="footer"></div>
</body>
</html>

124

2. -

: ,
- , connect.php.
(.4.1) MySQL.
, connect.html .
CSS. -
? . CSS.
,
.

.4.1. MySQL

, : ! , , , .4.2.

. 4.2. MySQL

4. PHP MySQL

125

, PHP-
, .
- : MySQL , ?
PHP, .


, : mysql_ :
, - . - , false,
(, null nil).
, MySQL

, PHP-. mysql_select_db.

mysql_ . : www.php.net/manual/ru/ref.mysql.php. -
, ,
.

-
, die PHP-,
. PHP
, :
mysql_connect("___",
"_", "");

, , ,
die.
: die - ,
,
, ,
. ,
die , , ,
:
Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

, , , , die.
, - .

126

2. -

,
-, ,
CSS-
. die.
PHP , , . ,
die , . , -
, , .
, die ( ) ,
.
,
.
die. ,
, , 7. die
.
mysql_select_db , , ,
USE
false. , connect.php:
<?php
mysql_connect("___",
"__", "_")
or die("<p> : " .
mysql_error() . "</p>");
echo "<p> MySQL!</p>";
mysql_select_db("___")
or die("<p> bmclaugh: " .
mysql_error() . "</p>");
echo "<p> MySQL bmclaugh.</p>";

?>

. die , , ,
. , ,
.

4. PHP MySQL

127

. connect.html
(
USE). .4.3.
: SQL.

. 4.3. MySQL,


SHOW
,
. ,
MySQL, ,
.
.
HTML
- .
, .
connect.php :
<?php
//
$result = mysql_query("SHOW TABLES;");

?>

PHP MySQL:
mysql_query. , -


SQL
. SQL, SQL-:
SHOW TABLES;

SQL-
.

128

2. -



die? ?
, - ,
. : ,
mysql_query, $result. ,
. , SHOW TABLES, - .
, $result false, ,
, mysql_ false.
, false,
:
<?php
//
$result = mysql_query("SHOW TABLES;");
if ($result === false) {
die("<p> : " . mysql_error() . "</p>");
}

?>

, PHP-
. === PHP ,
, , false. PHP
-, ,
: !. , ,
$some-variable false,
: if (!$some-variable). ! : ,
$some-variable false.
! not (). ,
: if not $result, then die (
$result true, ).
, :
<?php
//
$result = mysql_query("SHOW TABLES;");
if (!$result) {
die("<p> : " . mysql_error() . "</p>");
}
?>

PHP ,
.

4. PHP MySQL

129

PHP . , ,
, ? , ... , ,
? ,
,
.
.
, , .
. PHP-,
PHP, .

, , SQL, :
<?php
//
$result = mysql_query("SHOWN TABLES;");
if (!$result) {
die("<p> : " . mysql_error() . "</p>");
}
?>

connect.html
(.4.4). - , ,
, ,
- .

. 4.4.

SQL-
, ,
, $result, . ,

130

2. -

. $result
- PHP- , .
,
PHP
, -, PHP.
:
mysql_query SQL- SHOW TABLES.
, PHP MySQL,
, SQL. ,
$result , :
. , , , mysql_query. : , mysql_query, $result
,
URL- Facebook ,
CREATE TABLE.
, PHP-.
- ; , PHP , . PHP
. , MySQL
, $result.
MySQL- mysql_fetch_row. , mysql_query, , SQL-.
.
1. SQL- .
2. mysql_query PHP-.
3. mysql_fetch_row, .
4. .
5. - .

, .

, $result. ,
mysql_fetch_row:
<?php
//
$result = mysql_query("SHOW TABLES;");
if (!$result) {

4. PHP MySQL

131

die("<p> : " . mysql_error() . "</p>");


}
echo "<p>, :</p>";
echo "<ul>";
while ($row = mysql_fetch_row($result)) {
// - $row
}
echo "</ul>";
?>

SHOW TABLES SHOWN TABLES,


, SQL.

PHP , ,
mysql_query, mysql_fetch_row. $result

.
while, , , . while ,
true. ,
$row, , SQL, mysql_fetch_row($result).
, mysql_fetch_row ,
$row while : ,
.
(ul ),
, -
:
<?php
//
$result = mysql_query("SHOW TABLES;");
if (!$result) {
die("<p> :" . mysql_error() . "</p>");
}
echo "<p>, :</p>";
echo "<ul>";
while ($row = mysql_fetch_row($result)) {
echo "<li>: {$row[0]}</li>";
}
echo "</ul>";
?>

132

2. -

.
$row mysql_fetch_row , ,
$_
REQUEST
2. , SQL-. SHOW
TABLES : $row[0]. ,
, $row[1], $row[2]
$row[10].
, $row
0,
echo. :
, echo?
:
while ($row = mysql_fetch_row($result)) {
echo "<li>: " . $row[0] . "</li>";
}

, ,
.

, (. PHP 2).


PHP
, . , , , . ,
,
{ }, PHP ,
"$row[0]".
.
connect.php, connect.html
, . .4.5
connect.php, ,
.
. , .

SHOW TABLES.
, ,

20, 30 100. , PHP-


MySQL.

4. PHP MySQL

133

. 4.5. connect.php



, connect.php . MySQL:
<?php
mysql_connect("___",
"__", "_")
or die("<p> : " .
mysql_error() . "</p>");
echo "<p> MySQL!</p>";
mysql_select_db("___")
or die("<p> bmclaugh: " .
mysql_error() . "</p>");
echo "<p> MySQL bmclaugh.</p>";
// ...
?>

134

2. -

,
, . ,
10 10.
.
. , ?
, ,
-, ,
? ,

PHP
-. , .
.
. ,
, - (, ) , .
, - , . ,
.
, ,
34 . , ,
.

, , (
):
<?php
mysql_connect($database_host, $username, $password)
or die("<p> : " .
mysql_error() . "</p>");
echo "<p> MySQL!</p>";
mysql_select_db($database_name)
or die("<p> bmclaugh: " .
mysql_error() . "</p>");
echo "<p> MySQL bmclaugh. </p>";
// ...
?>

4. PHP MySQL

135


- .
:
<?php
$database_host = ".._";
$username = "-_";
$password = "-";
$database_name = "---";
//
?>

? , -
. ,
. .



connect.php
- (
PHP), .
app_config.php. :
<?php
//
$database_host = ".._";
$username = "-_";
$password = "-";
$database_name = "---";
?>

app_config.php , ,
. , , app_config.php
scripts/. ,
ch04/scripts/, , ../../scripts/app_config.php
[__]/scripts/app_config.php. ,
PHP-, .

,
, - . - . ,

136

2. -

,
, -.
PHP-
. app_config.php,
PHP
-, .
? connect.php
, . connect.php connect.html,
(.4.6).

. 4.6.

, connect.php ,
$username $password. PHP,
- connect.php
app_config.php. :
<?php
require '../../scripts/app_config.php';
//
?>

PHP ../../scripts/app_config.php , mysql_connect. , require : , PHP,


, ,
.

, require ,
app_config.php. ,
require.

.
,
.

4. PHP MySQL

137

Require Include?
PHP require include.
, require, PHP . , , include
PHP ,
. , require
, include .
. ,
? , , .
, , (require) .

require, include. - , . , , ,
, .

,

: , -
. ? , . , PHP connect.php
:
mysql_connect($database_host, $username, $password)
or die("<p> : " . mysql_error() . "</p>");
//
$password = "hijinks";

, , - ,
app_config.php, mysql_
connect? $password,
. "hijinks",
.
, app_config.php
.
define. app_config.php :
<?php
//
define("DATABASE_HOST", "___");

138

2. -

define("DATABASE_USERNAME", "__");
define("DATABASE_PASSWORD", "_");
define("DATABASE_NAME", "___");
?>

, PHP .
DATABASE_HOST, PHP
"___". ! ,
- .
. ,
PHP
-. , ,
. $ ,
.
connect.php, , :
<?php
require '../../scripts/app_config.php';
mysql_connect(DATABASE_HOST, DATABASE_USERNAME, DATABASE_PASSWORD)
or die("<p> : " .
mysql_error() . "</p>");
echo "<p> MySQL!</p>";
mysql_select_db(DATABASE_NAME)
or die("<p> " . DATABASE_NAME .
mysql_error() . "</p>");
echo "<p> MySQL " . DATABASE_NAME .
"</p>";
// , SQL-...
?>

. PHP
, (
$).
(.),
PHP 2.

connect.php .
. , ,
connect.php.

4. PHP MySQL

139

app_config.php ,
.
, PHP-,
-. , ,
.

, ,

, app_config.php
connect.php.
connect.php,
?
?
, . . 10, 20, 50 , .
,
. .
.
. , ( ),
.
{ } ,
$row[0], die, HTML, ,
.

. , . - , . ,
, , , .
, ,
.
.
? :
, !
, ,
, -
.

140

2. -

,
: , , . , , - .
- . ,
. ,
, .
.
, .
, , ,
, .


SQL-
, SQL,
:
MySQL

. ,

PHP

- ,
,
-.
.
HTML-,
SQL-, , MySQL ,
. ,
PHP-, mysql_query,
.

HTML-

mysql_query , , :
HTML
-. , ,
, .
queryRunner.html:
<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>

4. PHP MySQL

141

<div id="example"> 4.2</div>


<div id="content">
<h1> SQL-</h1>
<p> SQL- :</p>
<form action="scripts/run_query.php" method="POST">
<fieldset>
<textarea id="query_text" name="query"
cols="65" rows="8"></textarea>
</fieldset>
<br />
<fieldset class="center">
<input type="submit" value=" " />
<input type="reset" value=" " />
</fieldset>
</form>
</div>
<div id="footer"></div>
</body>
</html>

, , . 4.7.

. 4.7. queryRunner.html

142

2. -

( )
, : MySQL
. .
run_query.php :
<?php
require '../../scripts/app_config.php';
mysql_connect(DATABASE_HOST, DATABASE_USERNAME, DATABASE_PASSWORD)
or die("<p> : " .
mysql_error() . "</p>");
echo "<p> MySQL!</p>";
mysql_select_db(DATABASE_NAME)
or die("<p> " . DATABASE_NAME .
mysql_error() . "</p>");
echo "<p> MySQL " .
DATABASE_NAME . "</p>";

?>

, .
. ,
MySQL?
.
app_config.php:
, .
, require
( ) .
. database_connection.php. ,
app_config.php, :
<?php
require 'app_config.php';
mysql_connect(DATABASE_HOST, DATABASE_USERNAME, DATABASE_PASSWORD)
or die("<p> : " .
mysql_error() . "</p>");
echo "<p> MySQL!</p>";
mysql_select_db(DATABASE_NAME)
or die("<p> " .
DATABASE_NAME . mysql_error() . "</p>");
echo "<p> MySQL " .
DATABASE_NAME . ".</p>";
?>

4. PHP MySQL

143

, app_config.php ,
. database_connection.php , app_config.php,
.

, ,
run_query.php:
<?php
require '../../scripts/database_connection.php';
?>

, ? ,
app_config.php . database_
connection.php. database_connection.php,
app_config.php.
.
, queryRunner.
html . , .

4.8. , - require !

. 4.8. require

, ( ) ,
, . -,
, .
. 100 1000 , .


SQL- ( )
- PHP ,
SQL. $_REQUEST, , ,
(. $_REQUEST 2),

144

2. -

,
. ,
mysql_query.
:
<?php
require '../../scripts/database_connection.php';
$query_text = $_REQUEST['query'];
$result = mysql_query($query_text);
if (!$result) {
die("<p> SQL-" . $query_text . ": " .
mysql_error() . "</p>");
}
echo "<p> :</p>";
echo "<ul>";
while ($row = mysql_fetch_row($result)) {
echo "<li>{$row[0]}</li>";
}
echo "</ul>";

?>

HTML-,
mysql_query . PHP- $result if,
, mysql_fetch_row
.

mysql_query?
, , MySQL,
,
( ),
mysql_query. ,
require?
: , mysql_query,
. , connect.php (. MySQL PHP-,
) SHOW TABLES,
queryRunner.html.
, mysql_query ,
, , , - .

4. PHP MySQL

145

mysql_query
SQL-.
,
mysql_query. , mysql_query
,
mysql_query .
- .
,
( 8), . ? -
. ,
mysql_query,
- .
, ,
, . .
? ? !
, , , .
,
.
:
, .
,
.

,
-
, , ,
urls.
SQL:
CREATE TABLE urls (id int, url varchar(100), description varchar(100));

,
:
CREATE TABLE urls (
id int,
url varchar(100),
description varchar(100)
)

(.4.9). SQL ,

146

2. -

. , .
SQL- ,
?

. 4.9. SQL-

. ? ,
(.4.10). ,
. ,
. .

. 4.10. -

4. PHP MySQL

147

, ? ,

CREATE. , .4.11.

. 4.11.

CREATE TABLE . MySQL , urls


! , , , :
mysql> describe urls;
+-------------+--------------+------+-----+---------+-------+
| Field
| Type
| Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| id
| int(11)
| YES |
| NULL
|
|
| url
| varchar(100) | YES |
| NULL
|
|
| description | varchar(100) | YES |
| NULL
|
|
+-------------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

:
<?php
require '../../scripts/database_connection.php';
$query_text = $_REQUEST['query'];
$result = mysql_query($query_text);
if (!$result) {
die("<p> SQL- " . $query_text . ": " .
mysql_error() . "</p>");
}
echo "<p> :</p>";
echo "<ul>";
while ($row = mysql_fetch_row($result)) {
echo "<li>{$row[0]}</li>";
}
echo "</ul>";
?>

148

2. -

if (!$result) , ,
$result false. while , .
, CREATE. ?
, ? MySQL
, .

,
SELECT
mysql_query : CREATE. , , MySQL , ,
urls . mysql_query
CREATE, false , , true, .
, .
$result true .
.
mysql_query
SQL
-, , CREATE, INSERT, UPDATE, DELETE, DROP
, true (
) false ( ).

SQL-, UPDATE DELETE, .


. : UPDATE
, DELETE .
,
.

, , , . , SQL, .
. .
, . .
1. HTML-.
2. mysql_query .
3. , false, SQL- .

4. PHP MySQL

149

4. false, ,
: CREATE, INSERT, UPDATE, DELETE DROP. (
, .)
5. , ,
true, .
6. , ,
.
, if
(, , if) :
$return_rows = false;
$location = strpos($query_text, "CREATE");
if ($location === false) {
$location = strpos($query_text, "INSERT");
if ($location === false) {
$location = strpos($query_text, "UPDATE");
if ($location === false) {
$location = strpos($query_text, "DELETE");
if ($location === false) {
$location = strpos($query_text, "DROP");
if ($location === false) {
// ,
// CREATE, INSERT, UPDATE, DELETE
// DROP. .
$return_rows = true;
}
}
}
}
}

if $location false
(= = =).

, , . , if,
, ,
if:
$location = strpos($query_text, "SEARCH_STRING");
if ($location === false) {
// SEARCH_STRING
}

150

2. -

, if , , CREATE, INSERT, UPDATE, DELETE DROP:


// if
if ($location === false) {
// , ,
// CREATE, INSERT, UPDATE, DELETE DROP.
// .
$return_rows = true;
}

? ,

, CREATE INSERT,
. ,
strpos.

, . . PHP- .
, .

,
SQL,
, $return_rows false,
true.
if
$returns_rows true,
, false,
.
$returns_rows :
<?php
// require
//
//
// ,
if ($return_rows) {
//
echo "<p> :</p>";
echo "<ul>";
while ($row = mysql_fetch_row($result)) {
echo "<li>{$row[0]}</li>";
}
echo "</ul>";
} else {

4. PHP MySQL

151

// . ,
// .
if ($result) {
echo "<p> :</p>"
echo "<p>{$query_text}</p>";
}

?>

, if ($return_rows) , if ($return_rows = = = true).


if ($result).

. ,
, .
if($return_rows), ,
- SELECT, ()
.
else if ,
.
if , , .

if($result). $result false. , , $result true,
:
if ($return_rows) {
//
echo "<p> :</p>";
echo "<ul>";
while ($row = mysql_fetch_row($result)) {
echo "<li>{$row[0]}</li>";
}
echo "</ul>";
} else {
// . ,
// .
echo "<p> :</p>"
echo "<p>{$query_text}</p>";
}

, ,
. .
, urls,
PHP
- . SQL-
DROP TABLE urls;. ,

152

2. -

, ,
(.4.12).

. 4.12.

run_query.php ,
, , .
, ,
,
.


, , , - .
:
DROP TABLE urls;

, DROP ,
, , :
,
.
? , :
drop table urls;

, :
$location = strpos($query_text, "DROP");
if ($location === false) {
// true, ,
// .
}

DROP, drop.
strpos , , , , d D.
DROP, drop dRoP.

4. PHP MySQL

153

, , . , , , SQL
.
: , SQL ,
, .
,
, . , ,
.
( )
.
:
$query_string
:
$return_rows = false;
$query_text = strtoupper($query_text);
$location = strpos($query_text, "CREATE");
// if

, drop table urls DROP table UrLS,


DROP TABLE URLS DROP .
! , .

, .
, -
. ,
iPhone .



,
, ,
, , DROP INSERT:
// . , .
echo "<p> :</p>"
echo "<p>{$query_text}</p>";

, , .4.13.

, ,
CREATE DROP TABLE
urls;. , DROP,
CREATE.

154

2. -

. 4.13. SQL- ( .4.12)

.4.12 .4.13, ,
. . ,
:
$query_text = strtoupper($query_text);

$query_text . - ? , ,
. :
$query_text .
, :
SELECT *
FROM users
WHERE last_name = "MacLachlan";

, :
SELECT *
FROM USERS
WHERE LAST_NAME = "MACLACHLAN";

. SELECT,
SQL
-, MacLachlan

MACLACHLAN. .
.
, mysql_query $query_text
.
.
- ,
, : , ,
.
, :
:

4. PHP MySQL

155

$return_rows = false;
$uppercase_query_text = strtoupper($query_text);
$location = strpos($uppercase_query_text, "CREATE");

:
$return_rows = false;
$uppercase_query_text = strtoupper($query_text);
$location = strpos($uppercase_query_text, "CREATE");
if ($location === false) {
$location = strpos($uppercase_query_text, "INSERT");
if ($location === false) {
$location = strpos($uppercase_query_text, "UPDATE");
if ($location === false) {
$location = strpos($uppercase_query_text, "DELETE");
if ($location === false) {
$location = strpos($uppercase_query_text, "DROP");
if ($location === false) {
// ,
// , CREATE, INSERT, UPDATE,
// DELETE DROP. .
$return_rows = true;
}
}
}
}
}

,
.
, , ,
SQL-. .
, :
, , . -
PHP.


, , run_query.php,
. , -
:
SELECT
FROM
WHERE
OR

*
registrar_activities
name = 'Update GPA'
name = 'Drop a class'

156

2. -

SELECT, , run_query.php
SQL , .
.
, update drop, , , ,
. - !
SQL.
CREATE, INSERT . , , .
if PHP or ():
if ($location = = = false ||
$location > 0) {

PHP . ,
: ($location = = = false)
( 0),
. , if,
. , ,
.
! ,
. , -
SQL:
CREATE TABLE urls (
id int,
url varch*ar(100),
description varchar(100)
);

: ( SELECT),
. : .
, : trim. ,
, :
$uppercase_query_text =
trim(strtoupper($query_text));

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

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

. , -
. - ,
, ,
, .
. , - - , , .
, , , .
, .
run_query.php .
if, ,
CREATE, UPDATE, INSERT, SELECT... ?

. ,
,
, , , .
,
strpos . : .
: ,
. .
.
run_query.php,

158

2. -

if,
$query_text, .
, ,
.

, ,
.
, .
, , , -
, .

,
strpos, , ,
. , strpos ,
UPDATE DROP, .
.

- , , . ,
"abcdefghijklmnopqrstuvwxyz",
, "abc". ,
.
, , -
. , "<a". .
, , .
, .


,
"a" "m". "a"
"a". , ?
PHP

, , preg_match (preg PHP regular (expressions),


). :
<?php
$string_to_search = "Martin OMC-28LJ";
$regex = "/OM/";
$num_matches = preg_match($regex, $string_to_search);

5.

159

if ($num_matches > 0) {
echo " !";
} else {
echo " . .";
}
?>

preg_match , ,
. ,
, preg_match
, , , .

. regex.php . :
--(08:25 $)-> php regex.php
!

, . :
, .
, .
, ,
. ("), ('), escape-,

PHP
, .
,
. , , .
, "/OM/" , OM.
, "/OM/" OM. om, Om OhM. , O M. , ,
.
preg_match . ,
, , .
, ,
. :
preg_match , 0 1. 0 , 1 ,
.
,
preg_match_all. preg_match("/Mr/", "Mr. Mranity") 1, preg_match_all("/Mr/", "Mr. Mranity") 2.

160

2. -

, preg_match preg_match_all,
, .
, www.php.net/manual/en/function.preg-match.php.

...
, -
, strpos. ,
. , . : |.

?

(My name is Bob) (I am a carpenter) . , .
.
? Im going to the bank. , Im going to the bank. PHP
, Im
I, m going to the bank - .
, , ,
:
, .
- , - -
. (\) .
Im going to the bank.
I\m going to the bank. \ PHP , , .
? ,
, MS-DOS 286?
\del C:\*.*\ Enter! ,
, PHP
, , : \*.
PHP , ,
.
.

5.

161

escape- , ,
: .
\del C:\\*.*\ Enter!
() (\), PHP
,
. , : (\n), (\t)

{$variable} $variable.
, .
, .
. :
?
: 99% .
, escape-
,
. , ,
.
,

:
/(Mr|Dr)\. Smith/

: (\).
, .
- . \. , .
/Mr. Smith/ Mr. Smith, Dr. Smith
. /(Mr|Dr). Smith/ Mr. Smith
Dr. Smith.
:
//
echo " : " . preg_match("/(Mr|Dr). Smith/", "Mr. Smith");
//
echo " : " . preg_match("/(Mr|Dr). Smith/", "Dr. Smith");

162

2. -

, run_query.php . . :
<?php
require '../../scripts/database_connection.php';
$query_text = $_REQUEST['query'];
$result = mysql_query($query_text);
if (!$result) {
die("<p> SQL-: " . $query_text . ": " .
mysql_error() . "</p>");
}
$return_rows = false;
$uppercase_query_text = strtoupper($query_text);
$location = strpos($uppercase_query_text, "CREATE");
if ($location === false) {
$location = strpos($uppercase_query_text, "INSERT");
if ($location === false) {
$location = strpos($uppercase_query_text, "UPDATE");
if ($location === false) {
$location = strpos($uppercase_query_text, "DELETE");
if ($location === false) {
$location = strpos($uppercase_query_text, "DROP");
if ($location === false) {
// ,
// CREATE, INSERT, UPDATE, DELETE DROP.
// .
$return_rows = true;
}
}
}
}
}

?>

if ($return_rows) {
//
echo "<p> :</p>";
echo "<ul>";
while ($row = mysql_fetch_row($result)) {
echo "<li>{$row[0]}</li>";
}
echo "</ul>";
} else {
// . ,
// .
echo "<p> :</p>";
echo "<p>{$query_text}</p>";
}

5.

163

if .
, :
<?php
// require
$return_rows = true;
if (preg_match("/(CREATE|INSERT|UPDATE|DELETE|DROP)/",
strtoupper($query_text))) {
$return_rows = false;
}
if ($return_rows) {
//
}
?>

, , .
run_query.php 4,
5.

, if. .
1. $return_rows false
true. , ,
.
, $return_rows true.
2. if preg_match. preg_match_all, , , , .
3. : SQL-, .
. ,
, CREATE, INSERT,
UPDATE, DELETE, DROP.
4. $query_
text, .
$query_text,
. - ,
strtoupper.
5. , preg_match 0, PHP
0 false. , preg_match 1, PHP true.

164

2. -

preg_match if
, if
.
6. if $return_rows false,
, .
, , ,
20 4.

.
, .
, .


run_query.
php , , .

4, , .
, :
if (preg_match("/(CREATE|INSERT|UPDATE|DELETE|DROP)/",
trim(strtoupper($query_text)))) {
$return_rows = false;
}

: .
, :
SELECT
FROM
WHERE
OR

*
registrar_activities
name = 'Update GPA'
name = 'Drop a class'

-
UPDATE DROP. SELECT
, UPDATE DROP,

.
, if , .
PHP
: , ,
.
(^),
:

5.

165

//
echo " : " . preg_match("/^(Mr|Dr). Smith/",
"Dr. Smith") . "\n";
//
echo " : " . preg_match("/^(Mr|Dr). Smith/",
" Dr. Smith") . "\n";

, /^(Mr|Dr). Smith/ Dr. Smith,


"Dr. Smith" (Mr. Smith ).
, ^
.
, :
if (preg_match("/^(CREATE|INSERT|UPDATE|DELETE|DROP)/",
trim(strtoupper($query_text)))) {
$return_rows = false;
}

. ,
$: , , :
//
echo " : " . preg_match("/^(Mr|Dr). Smith$/",
,
"Dr. Smith ") . "\n";
//
echo " : " . preg_match("/^(Mr|Dr). Smith$/",
"Dr. Smith") . "\n";

^ $ (/).
, , /^(Mr|Dr). Smith/$, PHP $,
. ,
, , .

, , ,
$, Dr. Smith.
, (
^(Mr|Dr)) ( Smith$).
^ , $ ,
, , ,
, .
, , . ,
PHP ( == ===),
or, |,
, .

166

2. -

trim strtoupper
, . $query_text , CREATE, INSERT
.
,
, (
) . i:
//
echo " : " . preg_match("/^(MR|DR). sMiTH$/i",
,
"Dr. Smith") . "\n";

, ,
, , . , run_query.php, :
$return_rows = true;
if (preg_match("/^(CREATE|INSERT|UPDATE|DELETE|DROP)/i",
trim($query_text))) {
$return_rows = false;
}

strtoupper,
i
. , . 5.1, DROP, .
,
, .
$query_text, .
: ,
.
? ,
trim $query_string.
.
: , - ?
. , .
1. ,
.
2.
(CREATE|INSERT|UPDATE|DELETE|DROP).

5.

167

CREATE, UPDATE, - ,
.

. 5.1. ,

, : . /^ Mr. Smith/
. Mr. Smith , Mr.Smith
.
. ,
? +. : , , :
//
echo " : " . preg_match("/^ (MR|DR). sMiTH$/i",
,
" Dr. Smith") . "\n";
//
echo " : " . preg_match("/^ (MR|DR). sMiTH$/i",
"
Dr. Smith") . "\n";

168

2. -

//
echo " : " . preg_match("/^ +(MR|DR). sMiTH$/i",
"
Dr. Smith") . "\n";

,
, , ,
. , .
:
//
echo " : " . preg_match("/^ +(MR|DR). sMiTH$/i",
"Dr. Smith") . "\n";

! , + . ,
*:
//
echo " : " . preg_match("/^ *(MR|DR). sMiTH$/i",
"Dr. Smith") . "\n";

, $query_text run_query.php ,
:
$return_rows = true;
if (preg_match("/^ *(CREATE|INSERT|UPDATE|DELETE|DROP)/i",
$query_text)) {
$return_rows = false;
}


.5.2. run_query.php
, ?
, ,
. , - : .
, :
SQL Enter.

DROP-,
. ,
Enter : \n, \r\n, , ,
\r.

5.

169

. 5.2.

: \n ,
\r . , Windows \r\n, Unix Linux \n,
Mac ( , , OS X) \r.
, - ,
.
\n, .

, ?
, \n*
, \r* .
\r\n? \r*\n*.
? \r*\n* *
Enter ,
, ... Enter, .
,
. :

170

2. -

. :
( ) , \r, \n . , .

?
,
, : CREATE, INSERT UPDATE
$query_text. ,
, $location = strpos($query_text, "CREATE");
if ?
,
if. -, , -.
,
, .
-, . ,
. . : ,
- , .
,
run_query.php.
: SQL - $query_
text. , , .
:
SELECT
FROM
WHERE
OR

*
registrar_activities
name = 'Update GPA'
name = 'Drop a class'

SELECT , , DROP.
, ,
.
- (\r|\n| )*,
|, or (), *.
, |
, ([ ]).
$return_rows = true;
if (preg_match("/^[ \t\r\n]*(CREATE|INSERT|UPDATE|DELETE|DROP)/i",
$query_text)) {
$return_rows = false;
}

5.

171

,
, \t . ,
,
,
.
,
[ \t\r\n] \s.
:
$return_rows = true;
if (preg_match("/^\s*(CREATE|INSERT|UPDATE|DELETE|DROP)/i",
$query_text)) {
$return_rows = false;
}

, . SQL-,
.5.2, . . ,
, - , .5.3.
?

. 5.3. ,
,

.
, mysql_query
,
\r\n .
, run_query.php, . :
SELECT *
FROM urls
WHERE description = 'home page'

,
. urls ,

172

2. -

- (.5.4).
. SQL,
. ,
, ,
PHP MySQL.

. 5.4.

, ,
SQL

- ,
.
. SQL . , . ,
, , :
-, MySQL .

:

, , .

, ^ $, preg_match,
+, * .


PHP

MySQL
. - ,
Google
, , , .
, . PHP
. PHP, HTML
, .

5.

173

PHP
, , , . ,
, .
.
,
. , JavaScript . JavaScript
, replace(), match(),
. , PHP,
.
HTML5.
HTML5 ,
. ,
PHP -.
- , . Ruby Ruby on Rails
( ), ,
, Cucumber, Capybara TestUnit.
, !
, ,
.
? , SQL, MySQL, , , PHP. ,
.

. PHP-
HTML-, MySQL
, . PHP, if for, ,
.

PHP
MySQL

-.
. ,
: , SQL ( ).
, ,
-. , .
-,
, , ,
, .

: Twitter, URL- Facebook


( .2.1). ,
, PHP-

6. -

175

, -:
HTML CSS .
,
. , PHP
MySQL .
:
, . , ,
, , ,
. .

, - HTML
. , create_user.html.

. ,
, . , ,
(.6.1). , .
HTML
.6.1 getFormInfo.php .
. , .
, .

. 6.1. getFormInfo.php

176

2. -


- : , . - ,
. , . ?
, .
: . : , ,
,
, , .
, . -
(..2.1). ,
, :
;
;
;
URL- Facebook;
Twitter.

: , .
,
, , , URL-
Facebook Twitter.
SQL- CREATE,
:
CREATE TABLE users (
user_id int,
first_name varchar(20),
last_name varchar(30),
email varchar(50),
facebook_url varchar(100),
twitter_handle varchar(20)
);

, MySQL -
. ,
.

, SQL- 3. ,
.
, : , .

6. -

177


, .
, .
, , ,
. , ,
, , , , .
, first_name last_name,
. ( ) , , , , . , .
, , . , .
; .
, , , . , ,
, , . . ,
, users , . ,
, .


id
user_id. .
, .
, ?

Twitter,
. , ,
( , Twitter ,
m97f-ss0).
: -,
. , ,

.
: , . ,
ID, .

178

2. -

user_id.
, .
.


, SQL, .
user_id
, ID?
( -
) , user_id users?
, , , .
,
-.
, . , MySQL
, . , ,
. ,
MySQL user_id 1029, , MySQL ,
1030 ID .
CREATE:
CREATE TABLE users (
user_id int AUTO_INCREMENT,
first_name varchar(20),
last_name varchar(30),
email varchar(50),
facebook_url varchar(100),
twitter_handle varchar(20)
);

. ID.
- , MySQL
user_id. MySQL
user_id.

ID
user_id MySQL
: users
user_id.
, .

6. -

179

,
.

, .
, . user_id,
user_id, 2048, ,
user_id, , user_id .
,
. ,
, , .
, ,
.
MySQL user_id AUTO_INCREMENT
user_id, .
MySQL AUTO_INCREMENT , , ,
.
- . , - MySQL
, . MySQL

, user_id :
CREATE TABLE users (
user_id int AUTO_INCREMENT PRIMARY KEY,
first_name varchar(20),
last_name varchar(30),
email varchar(50),
facebook_url varchar(100),
twitter_handle varchar(20)
);

, AUTO_
INCREMENT: user_id . , MySQL
. , SQL PRIMARY KEY:
CREATE TABLE users (
user_id int AUTO_INCREMENT,
first_name varchar(20),
last_name varchar(30),
email varchar(50),
facebook_url varchar(100),
twitter_handle varchar(20)
);

, MySQL

.6.2 phpMyAdmin.

180

2. -

. 6.2. phpMyAdmin

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

#1075, , MySQL, , ,
AUTO_INCREMENT, PRIMARY KEY. ,
MySQL , , , .
PRIMARY KEY,
.


, user_id, .
AUTO_INCREMENT ( ) , AUTO_INCREMENT . , :
. , MySQL
.
, ,
. , . Twitter Facebook
, ,
.

6. -

181

PHP- -
. ? - -? ,
, ?
, .
MySQL , .
, MySQL,
NULL, :
CREATE TABLE users (
user_id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
first_name varchar(20) NOT NULL,
last_name varchar(30) NOT NULL,
email varchar(50) NOT NULL,
facebook_url varchar(100),
twitter_handle varchar(20)
);

, MySQL
user_id, NOT NULL.
, , MySQL
.

AUTO_INCREMENT, ,
(,
, !).

NULL NOT NULL


users , NOT NULL,
, . users
: ,
? , - ( ,
, , ).
.
, ?
NOT NULL , . ,
NOT NULL.
NULL, : ,
, ,
, .

182

2. -

NOT NULL.
, ,
, , .
28 ,
. , Facebook Twitter,
: , , .
, :
, , . .
, .
. ,
, , .
: NOT NULL , . , :
null, ( ) . , , , ,
. ,
, ,
, -
NOT NULL.
SQL,
users. MySQL
- , phpMyAdmin, . .

DROP .
, DROP TABLE
users;. .
CREATE , .


, users,
AUTO_INCREMENT
. , - ,
.
PHP. , .
getFormInfo.php.
, :

6. -

183

<?php
$first_name = trim($_REQUEST['first_name']);
$last_name = trim($_REQUEST['last_name']);
$email = trim($_REQUEST['email']);
$facebook_url = str_replace("facebook.org", "facebook.com", trim($_
REQUEST['facebook_url']));
$position = strpos($facebook_url, "facebook.com");
if ($position === false) {
$facebook_url = "http://www.facebook.com/" . $facebook_url;
}
$twitter_handle = trim($_REQUEST['twitter_handle']);
$twitter_url = "http://www.twitter.com/";
$position = strpos($twitter_handle, "@");
if ($position === false) {
$twitter_url = $twitter_url . $twitter_handle;
} else {
$twitter_url = $twitter_url . substr($twitter_handle, $position + 1);
}
?>

create_user.php scripts/,
, ch06/ examples. create_user.html,
.
, ,
. ,
users.

create_user.php,
strpos
.

SQL-
, :
<?php
require '../../scripts/database_connection.php';
//
?>

184

2. -

database_connection.php echo ( ).
, ,
.

,
INSERT,
.
. ,
(, ) SQL
:
INSERT INTO users (first_name,
last_name,
email,
facebook_url,
twitter_handle)
VALUES ("Brett",
"McLaughlin",
"brett.m@me.com",
"http://www.facebook.com/bdmclaughlin",
"@bdmclaughlin");

SQL-
MySQL.

: . , , , .
, :
$insert_sql = "INSERT INTO users (first_name, last_name, " .
"email, facebook_url, twitter_handle) " .
"VALUES ('{$first_name}', '{$last_name}', '{$email}', " .
"'{$facebook_url}', '{$twitter_handle}');";

, ,
, . ,
.

, SQL. mysql_query
. ,
,
users, .
, , { } .

6. -

185


, , ,
( ) PHP

-, SQL:
<?php
//
$insert_sql = "INSERT INTO users (first_name, last_name, email,
facebook_url, twitter_handle) " .
"VALUES ('{$first_name}', '{$last_name}', '{$email}', " .
"'{$facebook_url}', '{$twitter_handle}');";
//
mysql_query($insert_sql);
?>

! . .
, users?
users, facebook_url, ?
, .
(, ) :
<?php
//
$insert_sql = "INSERT INTO users (first_name, last_name, email,
facebook_url, twitter_handle) " .
"VALUES ('{$first_name}', '{$last_name}', '{$email}', " .
"'{$facebook_url}', '{$twitter_handle}');";
//
mysql_query($insert_sql)
or die(mysql_error());
?>

die ,
- .
, ,
. , - ,
.6.3.
, .
SQL, ,
mysql_query. , die
.

186

2. -

. 6.3.

, , . , - , , .

- HTML- getFormInfo.php,
create_user.php, -
.

, , SQL :
SELECT user_id, first_name, last_name
FROM users;

:
+---------+------------+-----------+
| user_id | first_name | last_name |
+---------+------------+-----------+
|
1 | C. J.
| Wilson
|
+---------+------------+-----------+
1 row in set (0.00 sec)

6. -

187

phpMyAdmin, users , (.6.4).

. 6.4. users

, users ,
-,
( ) :
1.
, ,
.


, -,
. , getFormInfo.html
create_user.html, , .
FTP-.
-
. ,
. , .
, , .

,
users.

188

2. -

,
,
. ,
, , create_user.php ,
.
, CRUD , , . (CReate), (Update) (Delete) .
HTML- (create_user, update_user
..) , .


( ,
-), , . -
, , ,
.
getFormInfo.php:
<?php
// request
//
?>
<html>
<head>
<link href="../../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"> 6.1</div>
<div id="content">
<p> , :</p>
<p>
: <?php echo $first_name . " " . $last_name; ?><br />
: <?php echo $email; ?><br />
<a href="<?php echo $facebook_url; ?>"> Facebook</a>
<br />
<a href="<?php echo $twitter_url; ?>"> Twitter-</a>

6. -

189

<br />
</p>
</div>
<div id="footer"></div>
</body>
</html>

, , ,
.
Twitter
, URL . ,
, . ,
.
, , $twitter_handle. , ,

-, ,
. ?
URL, , -

, .
,
,
.
Twitter
.
, :
Name: <?php echo $first_name . " " . $last_name; ?><br />

:
? ,
, ,
?



, , . ,
, Twitter @
. , ,
.
. ?
,

190

2. -

,
, .

, ? ,
, . - ? .
, ,
.
? -,
. ,
, , , .
, ! ,
(, SQL- SELECT). , ( , ), ,

.
, :
<?php
// request
//
$get_user_query = "SELECT * FROM USERS WHERE ..."
mysql_query($get_user_query);
// HTML
?>
<!-- HTML- -->

$get_user_query .
,
WHERE, .

,
.
, , ,
.

6. -

191

, ,
.
?
, . : -
, ? , . , .
create_user.php
show_user.php. . ,
.
database_connection.php,
.
,
.
create_user.php, , , .
create_user.php ,
.


, : , , .
users,
. ( )
- .
PHP,
, . PHP
HTML.
- ,
.php, HTML

-, . HTML

, .php, PHP,
. - HTML, ,
-, ( ) HTML-.


.6.5 , .
, : .

192

2. -

. 6.5.

HTML (CSS
):
<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"></div>
<div id="content">
<div class="user_profile">
<h1>. . </h1>
<p>
<img src="images/cj_wilson.jpg" class="user_pic" />
- -
.
-, 2010
, 2011
. , ,

6. -

193

. </p>
<p> , ,
.
</p>
<p class="contact_info"> . .:</p>
<ul>
<li>...
<a href="wilson@texasrangers.com"> </a></li>
<li>...
<a href="http://www.facebook.com/pages/CJ-Wilson/127083957307281">
Facebook</a></li>
<li>... <a href="http://www.twitter.com/str8edgeracer">
Twitter </a></li>
</ul>
</div>
</div>
<div id="footer"></div>
</body>
</html>

, users.
.
Twitter .
, ,
, .

( ) , . , ,
, $first_name, ,
$last_name, $email .. :
<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"></div>
<div id="content">
<div class="user_profile">
<h1>$first_name $last_name</h1>
<p><img src="$user_image" class="user_pic" />
$bio</p>
<p class="contact_info"> $first_name:</p>
<ul>
<li>...
<a href="$email"> </a></li>
<li>...

194

2. -

<a href="$facebook_url">
Facebook</a></li>
<li>... <a href="$twitter_url">
Twitter</a></li>
</ul>
</div>
</div>
<div id="footer"></div>
</body>
</html>

, HTML PHP.
, . ,
, PHP. ,
, ,
.

, HTML, PHP.
, ,
, , ($bio) ($user_image),
, users.
, .
users . , -

,
.
create_user.html create_user.php, -

, .
, :

, .
, ? ,
users.

ALTER
: . .
.
, . ,
.
,
. SQL- ALTER:
ALTER TABLE users
ADD bio varchar(1000);

6. -

195

, . SQL-
( ALTER), , . , ADD, .
, : bio NOT NULL? (, , , NOT NULL .) ? (
HTML-- create_user ,
. .)
, ? ,
.


?
ALTER
( , show_user)
: , ?
users , - ,
.

. , , - bio NULL.
NULL .
, , -,
,
, . ,
.

. -, ,

. , , username,
NOT NULL. , , ?
?

196

2. -

, .
?
username ,
.
.
, ,
?
, ,
- , NEEDS_USERNAME (
),
, . , , ,
.
ALTER : - , , ,
. ,
. ( .)

. , . - .

:
, bio users HTML-,
PHP. , show_user.php
( ). create_user.php ( ). , , delete_user.php
( ) update_user.php ( ).
- PHP

. HTML

. , , , , ,
PHP-.
:
<html>
<head>
<link href="../../css/phpMM.css" rel="stylesheet" type="text/css" />

6. -

197

</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"></div>
<div id="content">
<div class="user_profile">
<h1>$first_name $last_name</h1>
<p><img src="$user_image" class="user_pic" />
$bio</p>
<p class="contact_info"> $first_name:</p>
<ul>
<li>...
<a href="$email"> </a></li>
<li>...
<a href="$facebook_url">
Facebook</a></li>
<li>... <a href="$twitter_url">
Twitter</a></li>
</ul>
</div>
</div>
<div id="footer"></div>
</body>
</html>

PHP scripts/.
ch06/scripts/, , scripts/
-, PHP- .

.
PHP? <?php ?>, , .
, ($), PHP,

HTML. HTML- , .
? SQL,
SELECT - .
? ,

?
.
, , ,
PHP -.
, <?php ?>.
PHP , HTML. URL
, . .6.6.

198

2. -

. 6.6.

HTML.
- ,
. PHP

. ,
, ,
.

, ,
link head . scripts/ CSS
HTML- -
ch06/.

show_user.php , HTML,
- HTML - .
-. , , ,
.

6. -

199

.
<?php ?>, :
PHP. echo,
:
<html>
<head>
<link href="../../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"></div>
<div id="content">
<div class="user_profile">
<h1><?php echo "{$first_name} {$last_name}"; ?></h1>
<p><img src="<?php echo $user_image; ?>" class="user_pic" />
<?php echo $bio; ?></p>
<p class="contact_info">
<?php echo $first_name; ?>:
</p>
<ul>
<li>...
<a href="<?php echo $email; ?>"> </a></li>
<li>...
<a href="<?php echo $facebook_url; ?>">
Facebook</a></li>
<li>... <a href="<?php echo $twitter_url; ?>">
Twitter</a></li>
</ul>
</div>
</div>
<div id="footer"></div>
</body>
</html>

: ,
($), . ,
(.6.7). ( PHP echo
. PHP
. ,
PHP : ,
.) .
,
, . ? - PHP? ,
,
, .

200

2. -

. 6.7. -


PHP- HTML.
<?php- ,
:
<?php
$first_name = ". .";
$last_name = "";
$user_image = "///.jpg";
$bio = " - -
.
-, 2010
, 2011
. , ,

. </p>
<p> , ,
.";
$email = "wilson@texasrangers.com";
$facebook_url = "http://www.facebook.com/pages/CJ-Wilson/127083957307281";

6. -

201

$twitter_url = http://www.twitter.com/str8edgeracer;
?>
<html>
<!-- HTML PHP -->
</html>

-
, .6.8. ,
, , ($), , ,
.

. 6.8. - .
:
,


SELECT
HTML.
. , , SELECT:
SELECT *
FROM users;

202

2. -


:
+---------+------------+-----------+----------------+--------------------------------------------------------+----------------+------+
| user_id | first_name | last_name | email
|
facebook_url
|
twitter_handle | bio |
+---------+------------+-----------+----------------+--------------------------------------------------------+----------------+------+
|
1 | . .
| | wilson@texasrangers.com | http://www.facebook.com/
pages/CJ-Wilson/127083957307281 |
@str8edgeracer | NULL |
+---------+------------+-----------+----------------+--------------------------------------------------------+----------------+------+
1 row in set (0.03 sec)

, , , . SELECT ,
,
.

. ,
, first_name last_name, email
.. $first_name, $last_name
.
: ,
? ,
. , , ?
show_user.php,
, ... ,
?
, , show_
user.php. .
create_user.html create_user.php.

.
.
, , ,
, , Facebook
Twitter.
? show_user.php , URL.
, , - show_user.php.

6. -

203


show_user.php, , . , , show_user.php - ,
. , ,
ID
, show_user.php
, .
, .
create_user.php, ID

show_user.php.
show_user.php .
, , show_user.php

ID .
show_user.php
ID
, ID

.
,
show_user.php. ,
ID ,
, $_REQUEST.
show_user.php :
<?php
$user_id = $_REQUEST['user_id'];
//
?>
<html>
<!-- HTML PHP -->
</html>

. ,
,
: user_id.
- SELECT WHERE:
SELECT *
FROM users
WHERE user_id = $user_id;

WHERE (,
USE


SQL
3).

204

2. -

: -
. : (*)
users, (), user_id
, $user_id.
, user_id 1 $user_id 1, . user_id, 1,
SELECT . : user_id
PRIMARY KEY (.
ID
), ,
. ,
, - , . ,
, .
, show_user .
PHP:
<?php
require '../../scripts/database_connection.php';
// ID
$user_id = $_REQUEST['user_id'];
// SELECT
$select_query = "SELECT * FROM users WHERE user_id = " . $user_id;
//
$result = mysql_query($select_query);
//
?>
<html>
<!-- HTML PHP -->
</html>

,
SELECT user_id . :
.

SQL-
$result, ? ,
, , ,
. , -

6. -

205

PHP-
.
SELECT- ,
, .
, ,
show_user.php .
, $result .
, $result false, SQL:
//
$result = mysql_query($select_query);
if ($result) {
// $result
} else {
die(" ID {$user_id}");
}

if ( ) . $result false, , - , , -, , $user_id,


.

, . , ,
if .
PHP-: mysql_fetch_array. SQL

-. , $result:
if ($result) {
$row = mysql_fetch_array($result);
//
//
} else {
die(" ID {$user_id}");
}

. , , ,
mysql_fetch_array $row. , mysql_fetch_array

SQL
- , . : , 1.
? . mysql_fetch_array ,
, .
1

Array .. . .

206

2. -

, mysql_fetch_array($result)
,
.

. , , ,
, .
mysql_fetch_array , .
mysql_fetch_array false, ,
.
mysql_fetch_array ,
. ,
( false, )
.

, $row
. , $row ,
$_REQUEST (. $_
REQUEST
2). , $_REQUEST,
, , .
, "first_name",
$_REQUEST['first_
name']. $row.
, SQL

-, .
, $row,
:
//
$result = mysql_query($select_query);
if ($result) {
$row = mysql_fetch_array($result);
$first_name
= $row['first_name'];
$last_name
= $row['last_name'];
$bio
= $row['bio'];
$email
= $row['email'];
$facebook_url
= $row['facebook_url'];
$twitter_handle = $row['twitter_handle'];
// $twitter_handle URL
$twitter_url = "http://www.twitter.com/" .
substr($twitter_handle, $position + 1);
//
$user_image = "///_.jpg";
} else {
die(" ID {$user_id}");
}

6. -

207

if , URL
Twitter. , URL
trim()
2,
Twitter .
, $user_image -
.
:
$user_image = ../../images/missing_user.png;
,
.

, !
, $result mysql_fetch_array,
.

ID
show_user.php
ID ,
ID

, . , , show_user.php.
, show_user.php? .
, .
$_REQUEST , , ,
URL . ,
show_user.php, show_user.php
.
, create_user.php , , .
. URL, : yellowtagmedia.com/phpMM/
ch06/scripts/show_user.php?
URL.
URL ?.
:
[]://[_]/[_]?[_]

URL: mysite.com/scripts/show_user.php?first_name=Lance.
$_REQUEST['first_name'] "Lance".
,

208

2. -

&. , URL:
mysite.com/scripts/show_user.php?first_name=Lance&last_name=McCollum.

C (show_user.php) ,
(?first_name=Lance&last_name=McCollum) .

, . ID
, ( , ), show_user.php URL,
yellowtagmedia.com/phpMM/ch06/scripts/show_user.php?user_id=1.
, ,
.6.9, SQL show_
user.php.

. 6.9.

, PHP, . $_REQUEST[user_id]
USER_ID user_Id.
.

, show_user.php .

6. -

209

, , ,
create_user.php. ,
show_user.php , .

, : INSERT
users,
show_user.php. , ,
show_user.php .
create_user.php, -
.

scripts/?
( ) scripts/ ,
, Perl CGI ( Common Gateway Interface, ,
,
).
, , . , -, ,
.
PHP .
show_user.php HTML, PHP,
, . ,
PHP , . ,
PHP-, HTML
URL PHP- .
,
HTML PHP. ,
Wordpress (wordpress.org wordpress.com) PHP. index.php,
index.html.
, scripts/? . , , , HTML-
PHP-. scripts/ , -
.

210

2. -

7 ,
scripts/, . , , - HTML,
CSS JavaScript, , , PHP. , PHP,
PHP- HTML.

, , , . bio,
. create_user.php,
, .
show_user.php
ID . ,
,
.


. create_
user.html ,
. , , Facebook?
<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"> </div>
<div id="content">
<h1> </h1>
<p>, :</p>
<form action="scripts/create_user.php" method="POST">
<fieldset>
<label for="first_name">:</label>
<input type="text" name="first_name" size="20" /><br />
<label for="last_name">:</label>
<input type="text" name="last_name" size="20" /><br />

6. -

211

<label for="email"> :</label>


<input type="text" name="email" size="50" /><br />
<label for="facebook_url">URL- Facebook:</label>
<input type="text" name="facebook_url" size="50" /><br />
<label for="twitter_handle"> Twitter:</label>
<input type="text" name="twitter_handle" size="20" /><br />
<label for="bio">:</label>
<textarea name="bio" cols="40" rows="10"></textarea>
</fieldset>
<br />
<fieldset class="center">
<input type="submit" value=" " />
<input type="reset" value=" " />
</fieldset>
</form>
</div>
<div id="footer"></div>
</body>
</html>

,
. -
create_user.php , . ,
create_user.html, .
<html>
<!-- -->
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"> </div>
<div id="content">
<h1> </h1>
<p>, :</p>
<form action="scripts/create_user.php" method="POST"
enctype="multipart/form-data">
<fieldset>
<!-- -->
<label for="user_pic"> :</label>
<input type="file" name="user_pic" size="30" />
</fieldset>
<!-- -->
</body>
</html>

,
HTML .

212

2. -

form,
. enctype multipart/formdata. , ,
, .
, .
, .
file,
,
. ,
. .

, :
? ,
. ,
, users?
? ,
.

.
, .6.10. , -

. 6.10. ,
, ,

6. -

213


.
, , ,
, , ,
.
,
create_user.php, .


, , , create_user.php.
bio,
INSERT, :
<?php
require '../../scripts/database_connection.php';
$first_name = trim($_REQUEST['first_name']);
$last_name = trim($_REQUEST['last_name']);
$email = trim($_REQUEST['email']);
$bio = trim($_REQUEST['bio']);
// ...
$insert_sql =
"INSERT INTO users (first_name, last_name, email, bio,
facebook_url, twitter_handle)
" .
"VALUES ('{$first_name}', '{$last_name}',
'{$email}', '{$bio}' " .
"'{$facebook_url}', '{$twitter_handle}');";
//
mysql_query($insert_sql);
?>

. bio , .

, , ALTER TABLE,
bio users.

, , create_user.html .

SELECT:
SELECT first_name, last_name, bio
FROM users;

214

2. -

:
| first_name | last_name | bio
|
|
| , 1966
Genesis. 7 .
1975, , 11
. , , (1984),
(1989), (2002).

, ,
. .
C. J. Wilson bio NULL,
, bio.

show_user.php,
- ID
.
:
<?php
// ,
//
mysql_query($insert_sql);
// ,
//
header("Location: show_user.php");
exit();
?>

header HTTP- (HTTP


HyperText Transfer Protocol, )
. , HTTP, ,
, -. ( HTTP
http://, URL
.) , .
:
show_user.php. , .
header .
- echo,
<html>, - . header
, .
URL. , , , http://www.
google.com ../../scripts/database_connection.php.
, show_user.php.

6. -

215

, . , header .
ID . ,
mysql_query, INSERT, ,
ID .
SELECT, , show_user.php.
show_user.php ID , ,
PHP: PHP-
mysql_insert_id. ,
, ,
ID
INSERT , AUTO_INCREMENT.
mysql_insert_id.
, : ID
SELECT - .
mysql_insert_id , , ,
. INSERT,
myql_query, ,
.
ID .
URL, , URL :
<?php
// ,
//
mysql_query($insert_sql);
// ,
//
header("Location: show_user.php?user_id=" . mysql_insert_id());
?>

. create_user.php ,
.

:
("Location: show_user.php?user_id={mysql_insert_id()}");
, . PHP
, :
("Location: show_user.php?user_id={$user_id}");
.

.
,

216

2. -

create_user.php, show_
user.php, . .6.11
.

. 6.11.

, . , , .
. ,
. ,
.
HTML

, CSS

JavaScript

. -!


( )
. ? - , , . ?

6. -

217

, .6.11,
Enter,
HTML
. Enter HTML- <p></p>.
, ,
, .
, . Enter
\r \n
.
show_user.php Enter HTML <p>, preg_replace:
<?php
//
// SELECT
if ($result) {
$row = mysql_fetch_array($result);
$first_name
= $row['first_name'];
$last_name
= $row['last_name'];
$bio
= preg_replace("/[\r\n]+/", "</p><p>", $row['bio']);
$email
= $row['email'];
$facebook_url
= $row['facebook_url'];
$twitter_handle = $row['twitter_handle'];
// URL Twitter
}
?>
// HTML-

[\r\n]+, [\r\n]*. *
, , ,
</p><p> . + ,
\r \n ( ) ,
</p><p>.

.
,
,
\r, \n \r\n. , .
, show_user.php:
<?php
require '../../scripts/app_config.php';

218

2. -

require '../../scripts/database_connection.php';
// ID
$user_id = $_REQUEST['user_id'];
// SELECT
$select_query = "SELECT * FROM users WHERE user_id = " . $user_id;
//
$result = mysql_query($select_query);
if ($result) {
$row = mysql_fetch_array($result);
$first_name
= $row['first_name'];
$last_name
= $row['last_name'];
$bio
= preg_replace("/[\r\n]+/", "</p><p>", $row['bio']);
$email
= $row['email'];
$facebook_url
= $row['facebook_url'];
$twitter_handle = $row['twitter_handle'];
// $twitter_handle URL
$twitter_url = "http://www.twitter.com/" .
substr($twitter_handle, $position + 1);
//
$user_image = "../../images/missing_user.png";
} else {
die(" ID {$user_id}");
}
?>
<html>
<head>
<link href="../../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"></div>
<div id="content">
<div class="user_profile">
<h1><?php echo "{$first_name} {$last_name}"; ?></h1>
<p><img src="<?php echo $user_image; ?>" class="user_pic" />
<?php echo $bio; ?></p>
<p class="contact_info">
<?php echo $first_name; ?>:
</p>
<ul>
<li>...
<a href="<?php echo $email; ?>"><?php echo $email; ?></a></li>
<li>...

6. -

219

<a href="<?php echo $facebook_url; ?>">


Facebook</a></li>
<li>... <a href="<?php echo $twitter_url; ?>">
Twitter </a></li>
</ul>
</div>
</div>
<div id="footer"></div>
</body>
</html>

, , .6.12, , .

. 6.12.

,
. ? , .
HTML
? , . , , . , .

220

2. -

,
?
HTML create_user.html,
create_user.php,
show_user.php . , first_name
HTML, PHP MySQL ( , SQL). - , firstName,
user_firstName first_name.
, . , ,
.
:
HTML, PHP MySQL?
. : ,
PHP, ?
:
. Java
.
Java firstName, first_name.
C++, PHP , Ruby,
, .
SQL .
:
, , ,
. ,
HTML- .
PHP , ,
.

-
-

7. - ( )
8.
9.
10. ,

( )

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

- .
die , ,
, ,
, .
URL-
Facebook,

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

: JavaScript,
.
.

, ?
.7.1.
. , , .
,

7. - ( )

223

. .
, ,
, , , !
, .
,
.

. 7.1.

. URL show_user.php,
ID . .7.2 ,

. 7.2.
, ,

224

3. - -

. , , , ,
ID .
, . :
.


, , HTML: ,

PHP
. , , , .
, PHP
.
, HTML- show_error.html.
, :
<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"> </div>
<div id="content">
<h1> </h1>
<p></p>
</div>
<div id="footer"></div>
</body>
</html>

(.

7.3), .

.
, ,
. ,
, .

7. - ( )

225

. 7.3.

?
, : ,
? .
?
?


. , . .
,
MySQL ?
#1054 - Unknown column 'firstname' in 'field list'

, . MySQL PHP-, .
:
, .

, ,
: ? ? ?
? ?!

226

3. - -

? , , .

, , ,
:
, .

. , - .
,
.


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

. 7.4. ,

7. - ( )

227

. .7.4.
. (
. . .)
, , ,
, .
,
. ,
1282: .
, ,
,
:
<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"></div>
<div id="content">
<h1> ...</h1>
<p><img src="../images/error.jpg" class="error" />...
. ,
.
- ,
<a href="mailto:info@yellowtagmedia.com"></a>,
.</p>
<p> , ,
, <a href="javascript:history.go(-1);"> .</a>
,
. , . ...
.
.</p>
</div>
<div id="footer"></div>
</body>
</html>

, ,
. : , ,

228

3. - -

,
, .
.7.5. ,
.7.3, .

. 7.5.

,
. , ,
, . ,
, , !

,
, PHP-,
, .
, , .
,
. , , .

7. - ( )

229

( - , )
.
. .

! , ?
, ,
. .
, , , .


. , , .
, (
) ,
.
,
,
,
. ,
, .
, , , ,
24 36 - ,
.
, !
,
, . .
, ,
, ,
.
, ,
:
! , ,
.
, .
,
, .

230

3. - -


PHP
, :
, - .
, . , .7.5
. .
, , :
<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"></div>
<div id="content">
<h1> ...</h1>
<p><img src="../images/error.jpg" class="error" />...
. , <span class="error_message">
.</span></p>
<p> ,
.
- ,
<a href="mailto:info@yellowtagmedia.com"></a>,
.</p>
<p> , ,
, <a href="javascript:history.go(-1);"> .</a>
,
. , . ...
.
.</p>
</div>

<div id="footer"></div>
</body>
</html>

, .7.6,
, , -

7. - ( )

231

.
, .7.5 ,
. -,
, .
, , . -,
CSS-,
.

. 7.6.

PHP

HTML
. ( , , )

. . , HTML

232

3. - -

PHP-, ,
,
.
<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"></div>
<div id="content">
<h1> ...</h1>
<p><img src="../images/error.jpg" class="error" />
<?php echo $error_message; ?>
<span></p>
<p> ,
.
- ,
<a href="mailto:info@yellowtagmedia.com"></a>,
.</p>
<p> , ,
, <a href="javascript:history.go(-1);"> .</a>
,
. , . ...
.
.</p>
</div>
<div id="footer"></div>
</body>
</html>

show_error.php. :
HTML-.
7. ,
, scripts/
.

,
phpMM/scripts/, phpMM/ .

. ?
, ? , $_REQUEST.

7. - ( )

233

<?php
$error_message = $_REQUEST['error_message'];
?>
<html>
<!-- HTML PHP -->
</html>

? ,

PHP
. , . ,
,
PHP, , show_error.php.


. URL . URL
:
http://www.yellowtagmedia.com/phpMM/scripts/
show_error.php?error_message=There's%20been%20a%20problem
%20connecting%20to%20the%20database.

URL . ,
,
%20. , .

, (.7.7).

,
$_REQUEST,
. ,
?,
&.

, ,
,
,
show_error.php. .
, .
: ,
, . .
:
$error_message = preg_replace_all("/\\\\/", '',
$_REQUEST['error_message']);

234

3. - -

. 7.7.

PHP

, . , ,
\\\\ \. ,

PHP
, .


, - , ,
. .
, , , .
, . error_message
? , .7.8. ...,
.

7. - ( )

235

. 7.8. ,

show_error.php scripts/?

scripts/ . , , - create_user.html
create_user.php show_user.php. , HTML- PHP-
, .
show_error.php scripts/. ?
, show_error.php HTML-.
, .
database_connection.php,
scripts/. () , ,
HTML-.

236

3. - -

: ? PHP- HTML...
? JavaScript, CSS?
.
. ,
.
users/, ,
: show_user.php, create_user.php create_user.html.
, groups/ social/ ..
, . , , ,
(CSS, PHP - ). , ,
, ,
. , .
, , PHP-.
scripts/. , ,
, scripts/ utilities/.
, 50 100,
.
, .
: , :
<?php
$error_message = preg_replace_all("/\\\\/", '',
$_REQUEST['error_message']);
if (!isset($error_message)) {
$error_message = " - .";
}
?>
<html>
<!-- HTML PHP -->
</html>

isset , :
$error_message , ,
( !), $error_message
. isset true, - null.
: $
error_message , $_REQUEST['error_message'].
null, isset
.

7. - ( )

237

, URL,
(.7.9).

. 7.9.

, , .
,
. ,
span-, ,
, , .



, .
, , .
error_message
... ,
. ? .

238

3. - -


URL

, , -, .
, URL,
-. ,
-, :
http://yellowtagmedia.com/phpMM/ch07/show_error.php?error_message=
%3Ca%20href=%22http://www.syfy.com/beinghuman%22%3E %F9%E5%EB%EA%ED%E8%F2
%E5%20%E7%E4%E5%F1%FC%2C%20%F7%F2%EE%E1%FB%20%EF%EE%EB%F3%F7%E8%F2%FC%20
%EE%EF%E8%F1%E0%ED%E8%E5%20%EE%F8%E8%E1%EA%E8%3C/a%3E

.
, ,
: yellowtagmedia.com. yellowtagmedia.com . , ,
. ,
.7.10.

. 7.10. ,

7. - ( )

239

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

. 7.11. :
( , ),

SyFy (Being
Human) .
, ,
, ,
, , , . .

CSS, yellowtagmedia.com,
, ,
.

240

3. - -

,
,
. URL, :
http://yellowtagmedia.com/phpMM/ch07/show_error.php?error_message=
%3Ca%20href=%22http://www.syfy.com/beinghuman%22%3E %F9%E5%EB%EA%ED%E8%F2
%E5%20%E7%E4%E5%F1%FC%2C%20%F7%F2%EE%E1%FB%20%EF%EE%EB%F3%F7%E8%F2%FC%20
%EE%EF%E8%F1%E0%ED%E8%E5%20%EE%F8%E8%E1%EA%E8%3C/a%3E

error_message.
... , .
, URL :
http://yellowtagmedia.com/phpMM/ch07/show_error.php?error_message=<a
href="http://www.syfy.com/beinghuman"> ,
</a>

, . ,
.
, PHP, . ... .
, ,
. ,
, 13, , .

, .
, . ,
: , -
. , , ,
. 13, , .


,
?
, . ,
. , ,
, . - !

7. - ( )

241


, .
.
, ,
.

,
PHP
,
. , , :
echo ", {$first_name}\n\n";
$query = "SELECT * FROM users WHERE first_name = {$first_name}";

, $first_name .
, . , ,
isset, , -
, . , .
.
PHP:
.
, PHP, ,
.

- , -, - PHP, .
.

,
display_error.php :
<?php
echo ", {$first_name}\n\n";
$query = "SELECT * FROM users WHERE first_name = {$first_name}";
echo "{$query}\n\n";
?>

242

3. - -

, - , $first_name. , , ,
, .
, :
$ php display_error.php
,
SELECT * FROM users WHERE first_name =

, ? PHP ,
. , ,
.
( ,
!) ,
$first_name.
PHP- error_reporting.
display_error.php :
<?php
error_reporting(E_ALL);
echo ", {$first_name}\n\n";
$query = "SELECT * FROM users WHERE first_name = {$first_name}";
echo "{$query}\n\n";
?>

E_ALL . E_ALL
. E_ERROR,
E_WARNING, E_PARSE E_NOTICE,
( ). www.php.net/manual/en/function.errorreporting.
php. E_ALL
.
, :
$ php display_error.php
PHP Notice: Undefined variable: first_name in yellowtagmedia_com/phpMM/ch07/
display_error.php on line 5
Notice: Undefined variable: first_name in yellowtagmedia_com/phpMM/ch07/display_error.php on line 5
,
PHP Notice:

Undefined variable: first_name in yellowtagmedia_com/phpMM/ch07/

7. - ( )

243

display_error.php on line 6
Notice: Undefined variable: first_name in yellowtagmedia_com/phpMM/ch07/display_error.php on line 6
SELECT * FROM users WHERE first_name =

PHP
, .
,
. , .

, , ,
.
PHP .
, .


: .
.
, ,
.
, :
, database_connection.php, .
- ,
. : app_config.php,
database_connection.php ,
. .

, , -
app_config.php . .
.

app_config.php, scripts/. show_error.php database_


connection.php. error_reporting, :
<?php
//
//
error_reporting(E_ALL);
?>

244

3. - -

:
<?php
require '../scripts/app_config.php';
echo ", {$first_name}\n\n";
$query = "SELECT * FROM users WHERE first_name = {$first_name}";
echo "{$query}\n\n";
?>

, , error_reporting
display_error.php, app_config.php.

.
, .

,
( - )
, , ,
, , , ... app_config.php. , ,
?
,
- .
, ,
, , -
... , . app_config.php.
( )
, .
app_config.php,
. (
app_config.php.) , , .



, . :
, .
app_config.php show_error.php:

7. - ( )

245

<?php
require 'app_config.php';
$error_message = preg_replace_all("/\\\\/", '',
$_REQUEST['error_message']);
if (!isset($error_message)) {
$error_message = " - .";
}

?>

<html>
<!-- HTML PHP -->
</html>

show_error.php , . show_error.php
, .
.7.12, .

. 7.12. :
!

, , , , $error_
message ($_REQUEST['error_message']), (null).

246

3. - -

.
,
(null) :
<?php
require 'app_config.php';
if (isset($_REQUEST['error_message'])) {
$error_message = preg_replace_all("/\\\\/", '',
$_REQUEST['error_message']);
} else {
$error_message =
" - .";
}

?>

<html>
<!-- HTML PHP -->
</html>


PHP
null isset. isset , null.
. , , (..7.9).
: , , ,
,
. - : . : -
-. , , ,
, .
? ,
. , , ,
. , , .

: , , .

.
app_config.php :

7. - ( )

247

<?php
//
define("DEBUG_MODE", true);
//
//
if (DEBUG_MODE) {
error_reporting(E_ALL);
} else {
//
error_reporting(0);
}
?>

. DEBUG_MODE
( ) .

require require_once
, database_connection.php
:
require 'app_config.php';

, , :
require '../../scripts/database_connection.php';

app_config.php. ,
app_config.php ,
database_connection.php, app_config.php .
( ) . , app_config.php ,
, , app_config.php . , .

database_connection.php. , database_connection.php
. , app_config.php.
, , .

. :

248

3. - -

app_config.php, database_connection.php,
app_config.php. , ,
, app_config.php .

,
, PHP :
//
define("DATABASE_HOST", "db.host.com");
define("DATABASE_USERNAME", "username");
define("DATABASE_PASSWORD", "super.secret.password");
define("DATABASE_NAME", "db-name");

, ,
require :
Notice: Constant DATABASE_HOST already defined in yellowtagmedia_com/phpMM/
scripts/app_config.php on line 4
Notice: Constant DATABASE_USERNAME already defined in yellowtagmedia_com/
phpMM/scripts/app_config.php on line 5
Notice: Constant DATABASE_PASSWORD already defined in yellowtagmedia_com/
phpMM/scripts/app_config.php on line 6

,
require require_once.
, , , require:
// ,
require '../scripts/app_config.php';

, app_config.php,
require_once:
// database_connection.php
require_once '../scripts/app_config.php';

require_once ,
( include require),
, .
app_config.php.
: , create_
user.php, , show_user.php.
, , , require, , .
app_config.php? database_connection.php?
-,
require_once . , -

7. - ( )

249

app_config.php .
: ,
require .
require_once,
- . -
, .

, require_once,
, require.
, ,
PHP- require_once.

,
, , -
: ,
-
. . app_config.php DEBUG_MODE,
.

. , ( , PHP),
.
,
, .
, debug_print,
:
function debug_print($message) {
if (DEBUG_MODE) {
echo $message;
}
}

app_config.php,
. :
, , , $message
.
! .
, ,

.

250

3. - -

show_error.php :
<?php
require 'app_config.php';
if (isset($_REQUEST['error_message'])) {
$error_message = preg_replace_all("/\\\\/", '',
$_REQUEST['error_message']);
} else {
$error_message = " - .";
}
if (isset($_REQUEST['system_error_message'])) {
$system_error_message = preg_replace("/\\\\/", '',
$_REQUEST['system_error_message']); } else {
$system_error_message = " .";
}

?>

. error_reporting,
- .

HTML
:
<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"></div>
<div id="content">
<h1> ...</h1>
<!--
-->
<?php
debug_print("<hr />");
debug_print("<p>
:
<b>{$system_error_message}</b></p>");
?>
</div>
<div id="footer"></div>
</body>
</html>

7. - ( )

251

. ,
app_config.php. .



,
PHP ( error_reporting),
( debug_print).
. .
-
4: connect.html connect.php.

, .
connect.html connect.php
scripts/ connect.php connect.html.
require_once app_config.php app_config.
php connect.php. , ,
PHP, , .


show_error.php
, :
<?php
require '../scripts/app_config.php';
mysql_connect(DATABASE_HOST, DATABASE_USERNAME, DATABASE_PASSWORD)
or die("<p> : " .
mysql_error() . "</p>");
// ....
?>

mysql_connect , . .
:
if (!mysql_connect(DATABASE_HOST,
DATABASE_USERNAME, DATABASE_PASSWORD)) {
$user_error_message = " , " .
" , " .
" .";
$system_error_message = mysql_error();
header("Location: ../scripts/show_error.php?" .

252

3. - -

"error_message={$user_error_message}&" .
"system_error_message={$system_error_message}");
exit();
}

, ,
. , , ,
. $user_
error_message, header URL- .

,
PHP
-, , .
, :
if (!mysql_connect(DATABASE_HOST, DATABASE_USERNAME, "foo")) {
//
}

connect.html , connect.
php. (.7.13).

. 7.13. , ,

7. - ( )

253

, , DEBUG_MODE app_config.php
true, ,
, .

! ,
.
DEBUG_MODE app_config.php false:
//
define("DEBUG_MODE", false);

connect.html connect.php,
, (.7.14).

. 7.14. ,


. ,
- ? ,
,
,
.

254

3. - -


, ? . ,
connect.php:
if (!mysql_connect(DATABASE_HOST,
DATABASE_USERNAME, DATABASE_PASSWORD)) {
$user_error_message = " , " .
" , " .
" .";
$system_error_message = mysql_error();
header("Location: ../scripts/show_error.php?" .
"error_message={$user_error_message}&" .
"system_error_message={$system_error_message}");
exit();
}

, .
, , . ,
, . , ?
mysql_connect(DATABASE_HOST, DATABASE_USERNAME, DATABASE_PASSWORD)
or die("<p>Error connecting to database: " . mysql_error() . "</p>");

, ,
. , , .
?
, .
, :
if (!mysql_connect(DATABASE_HOST,
DATABASE_USERNAME, DATABASE_PASSWORD)) {
$user_error_message = " , " .
" , " .
" .";
$system_error_message = mysql_error();
header("Location: ../scripts/show_error.php?" .
"error_message={$user_error_message}&" .
"system_error_message={$system_error_message}");
exit();
}

, , , .
, header URL
. , debug_print?

7. - ( )

255

app_config.php, :
<?php
//
//
//
function debug_print($message) {
if (DEBUG_MODE) {
echo $message;
}
}
function ($user_error_message, $system_error_message) {
header("Location: show_error.php?" .
"error_message={$user_error_message}&" .
"system_error_message={$system_error_message}");
exit();
}
?>

, debug_print.
,
, .
exit.
,
, header , . , PHP
, .
connect.php:
if (!mysql_connect(DATABASE_HOST, DATABASE_USERNAME, "foo")) {
handle_error(" , , " .
" .",
mysql_error());
}

, ,
. :
mysql_connect(DATABASE_HOST, DATABASE_USERNAME, "foo")
or handle_error(" , , " .
" .",
mysql_error());

if
or die ,
handle_error.

256

3. - -


, .7.15.

. 7.15. PHP

connect.php
. , , ,
show_error.php, . ?
, PHP.
- , URL

-, .php, PHP-. ,
PHP

- . , - , URL, .php, . URL PHP-.



URL
.
PHP
: . , : No input file specified ( ).
: ?
app_config.php:
function handle_error($user_error_message, $system_error_message) {
header("Location: show_error.php?" .
"error_message={$user_error_message}&" .
"system_error_message={$system_error_message}");
}

show_error.php app_config.php.
app_config.php , show_error.php,
.
connect.php, (
) ch07/. ,
show_error.php ../scripts/show_error.php. ,
handle_error app_config.php,
connect.php. ? show_error.php .
app_config.php connect.php,
, , , .
- handle_error ?
, ,
, show_error.php ,
, .

7. - ( )

257


, . , ,
show_error.php, (..). show_error.php
../scripts/show_error.php. ,
.
, ,
.
/, , ,
-. /scripts/show_error.php.
app_config.php :
//
define("SITE_ROOT", "/phpMM/");

handle_error.
app_config.php
handle_error debug_print:
<?php
//
define("DEBUG_MODE", false);
//
define("SITE_ROOT", "/phpMM/");
//
define("DATABASE_HOST", "database.host.com");
define("DATABASE_USERNAME", "username");
define("DATABASE_PASSWORD", "super.secret.password");
define("DATABASE_NAME", "database-name");
//
if ($debug_mode) {
error_reporting(E_ALL);
} else {
//
error_reporting(0);
}
function debug_print($message) {
if (DEBUG_MODE) {

258

3. - -

echo $message;
}
}
function handle_error($user_error_message, $system_error_message) {
header("Location: " . SITE_ROOT . "scripts/show_error.php?" .
"error_message={$user_error_message}&" .
"system_error_message={$system_error_message}");
}
?>

,
SITE_ROOT URL header
(.).

show_error.php connect.php! , .7.14.



die handle_error. database_connection.php,
handle_error:
<?php
require 'app_config.php';
mysql_connect(DATABASE_HOST, DATABASE_USERNAME, DATABASE_PASSWORD)
or handle_error(" , , " .
" .",
mysql_error());
mysql_select_db(DATABASE_NAME)
or handle_error(" .",
mysql_error());
?>


?
, ? - . , - , ,
, require require_once
PHP-
.

7. - ( )

259

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


. , ,
- , .

.
PHP-, if
,
MySQL

, PHP

-. , ,
, -, .
, ,
. , . . ,
.
, - ,
. ,
, -, ,
.
(, , ), Facebook Twitter,
, .
. , , ,
.
, users, .
? .
debug_print handle_error,
.

8.

261

.
, , ,
-
. : , .


. ,
, .
6 (.8.1) , (.8.2),
: .

. 8.1.

, .

. (
Facebook
Twitter

? !)
, ? img HTML:
<img src="images/cj_wilson.jpg" class="user_pic" />

262

3. - -

. 8.2. ,

src. ,
. users , - ,
. , .
, Ryan Geyer @trenspot, ,
.
-
, ,
.

,

, ,
, , .
, : , . HTML, CSS JavaScript

8.

263

: , - PHP-. PHP - PHP, HTML, CSS JavaScript ,


. HTML, CSS JavaScript
, , -, PHP-, .
. ,
, . . , - , JPEG, GIF PNG, .
. URL - , ,
- - . , -, ,
. , , , -. , , - . ,
-.
, , , FTP-. . , .
. ,
-.
, ,
. .
- .
. PHP
, , .

HTML
HTML
PHP
-. ,
HTML
- .
, ,
.
create_user.html ,

6, , . , (. ,

264

3. - -

6),
:
<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"> </div>
<div id="content">
<h1> </h1>
<p>, :</p>
<form action="create_user.php" method="POST"
enctype="multipart/form-data">
<fieldset>
<label
<input
<label
<input
<label
<input
<label
<input
<label
<input
<label
<input
<label

for="first_name">:</label>
type="text" name="first_name" size="20" /><br />
for="last_name">:</label>
type="text" name="last_name" size="20" /><br />
for="email"> :</label>
type="text" name="email" size="50" /><br />
for="facebook_url">URL- Facebook:</label>
type="text" name="facebook_url" size="50" /><br />
for="twitter_handle"> Twitter:</label>
type="text" name="twitter_handle" size="20" /><br />
for="user_pic"> :</label>
type="file" name="user_pic" size="30" />
for="bio">:</label>

<textarea name="bio" cols="40" rows=10"></textarea>


</fieldset>
<br />
<fieldset class="center">
<input type="submit" value=" " />
<input type="reset" value=" " />
</fieldset>
</form>
</div>
<div id="footer"></div>
</body>
</html>

8.

265

(form action), ,
scripts/. HTML ch08/
.

enctype form
(input type) "file" user_pic.
, .
.8.3 ,
. - : .
22 , ? .
22

. - .

. 8.3. , ,

, .
: 1000000 -. , , , 20
30 Word 1. 20 .
,
, Flickr (www.flickr.com), -
. .

266

3. - -


"MAX_FILE_SIZE".
. 1,
1

000

000.
HTML
, 2, :
<input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
<label for="user_pic"> :</label>
<input type="file" name="user_pic" size="30" />

, file.
. . ( , , ,
.)

,
,
- (..8.3). : , .
PHP-, ,
, - . .8.4
Chrome: .

. 8.4.

, .
, , , .
PHP.

- .
create_user.php . C
:
<?php
require_once '../scripts/app_config.php';

8.

267

require_once '../scripts/database_connection.php';
$first_name = trim($_REQUEST['first_name']);
$last_name = trim($_REQUEST['last_name']);
$email = trim($_REQUEST['email']);
$bio = trim($_REQUEST['bio']);
$facebook_url = str_replace("facebook.org", "facebook.com", trim($_
REQUEST['facebook_url']));
$position = strpos($facebook_url, "facebook.com");
if ($position === false) {
$facebook_url = "http://www.facebook.com/" . $facebook_url;
}
$twitter_handle = trim($_REQUEST['twitter_handle']);
$twitter_url = "http://www.twitter.com/";
$position = strpos($twitter_handle, "@");
if ($position === false) {
$twitter_url = $twitter_url . $twitter_handle;
} else {
$twitter_url = $twitter_url . substr($twitter_handle, $position + 1);
}
$insert_sql = "INSERT INTO users (first_name, last_name, email, " .
"bio, facebook_url, twitter_handle) " .
"VALUES ('{$first_name}', '{$last_name}', '{$email}', " .
"'{$bio}', '{$facebook_url}', '{$twitter_handle}');";
//
mysql_query($insert_sql);
// ,
//
header("Location: show_user.php?user_id=" . mysql_insert_id());
exit();
?>

, .
app_config.php database_connection.php,
require require_once.


,
.
:
<?php
require_once '../scripts/app_config.php';

268

3. - -

require_once '../scripts/database_connection.php';
$upload_dir = SITE_ROOT . "uploads/profile_pics/";
$image_fieldname = "user_pic";
$first_name = trim($_REQUEST['first_name']);
//
//
// MySQL
?>

. SITE_ROOT, app_config.php.
, .
-, Terminal,
FTP-. SITE_ROOT
/, /uploads/profile_pics. SITE_ROOT yellowtagmedia_com/phpMM, yellowtagmedia_com/phpMM/
uploads/profile_pics.
:
$upload_dir = SITE_ROOT . "uploads/";
$image_fieldname = "user_pic";
// PHP-
$php_errors = array(1 => ' . , php.ini',
2 => ' . , HTML',
3 => ' ',
4 => ' .');

, .
array, ,
.
,
:
// PHP-
$php_errors = array(' . , php.ini',
' . , HTML',
' ',
' .');

, .
, $php_errors[0] , , '
. , php.ini'.

8.

269

, ,
, (. . 2).

(=>)? , PHP
. , ,
, $_REQUEST['user_pic']. $_REQUEST , (
HTML-) , .
user_pic
, profile_pic.jpg,
:
$_REQUEST = array('user_pic' => 'profile_pic.jpg');

PHP , .

, PHP .
, , ,
, , .

PHP-:
// PHP-
$php_errors = array(1 => ' . , php.ini',
2 => ' . , HTML',
3 => ' ',
4 => ' .');

, PHP

. , $php_errors[1]
' . , php.ini', PHP

$php_errors[0].
PHP

-? , , PHP

-. .
PHP $_REQUEST.
, $_FILES.
, $_REQUEST, . ,
$_FILES[$image_fieldname]
. (, $image_fieldname
create_user.php.)

270

3. - -

. $_FILES[$image_fieldname] , ,
.
$_FILES[$image_fieldname]['error']. 0
, , , .
, :
1
2
3
4

=>
=>
=>
=>

' . , php.ini'
' . , HTML'
' '
' .'

$php_errors :
, $_FILES[$image_fieldname]['error'],
.
, .
.

?
, : $_FILES ,
. , -
. , handle_error.
<?php
//
//
//
//
($_FILES[$image_fieldname]['error'] == 0)
or handle_error(" .",
$php_errors($_FILES[$image_fieldname]['error']));
// MySQL
// show_error.php
?>

($_FILES[$image_fieldname]['error']) 0, ,
.
, , , ,
$php_errors ,
.

app_config.php , DEBUG_
MODE true.

8.

271

, , , : if if. PHP :
($_FILES[$image_fieldname]['error'] == 0)

true, .
true, PHP or
, ,
handle_error.
:
if ($_FILES[$image_fieldname]['error'] != 0) {
handle_error(" .",
$php_errors[$_FILES[$image_fieldname]['error']]);
}

. , .

, if .
,

PHP.
. create_user.html
, 2.
iPhoto

, . , .
, .8.5.
, , .
- PHP,
handle_error
. ( ?) handle_error,
,
PHP-.

, , , , ,
. ,
, .
PHP, .

, .
$php_errors,
, HTML.

272

3. - -

. 8.5.

?
-
PHP, . ,
, ,
. , . , ,
- ,
, . ,
, , . (
/etc/passwd.)
,
,
, .
PHP
is_uploaded_file, , ,
HTTP
( - HTML-). ,
-, false ,
- .

8.

273

, - :
// ,
// ?
is_uploaded_file($_FILES[$image_fieldname]['tmp_name'])
or handle_error(" . !",
" : " .
"'{$_FILES[$image_fieldname]['tmp_name']}'");
// MySQL


,
. ,
, .
,
, .
.
PHP-. . , ,
- , , .
.
, , -
PHP . , .
($_FILES[$image_fieldname]): .
, .
: is_uploaded_file ,
. , , . ,
is_uploaded_file . , .
PHP ,
@ (
), :
// ?
@is_uploaded_file($_FILES[$image_fieldname]['tmp_name'])
or handle_error(" . !",
" : " .
"'{$_FILES[$image_fieldname]['tmp_name']}'");

274

3. - -

. ,
handle_error - .
,
.



, PHP , @. , , SQL- ,
URL.
, , -
, , .
@ , ,
.
.
, : ,
, .
, , @, , . : @
( ) or
. .
. ( !) ,
-. @, .
.
, @, or ,
, , 7. ,
(, , ).
,
, .

?
, ,
, - . :
, . Word,
- JavaScript .

8.

275

, PHP
. getimagesize,
. , . !
// ?
@getimagesize($_FILES[$image_fieldname]['tmp_name'])
or handle_error(" , " .
" .",
"{$_FILES[$image_fieldname]['tmp_name']} " .
" .");


.

HTTP
, . , , - .
:
$upload_dir = SITE_ROOT . "uploads/profile_pics/";

, .

, ,
. , ,
. , ,
, .
, - .
, , . - , .
, - . $upload_dir.
. - , ,
.


.

, Flickr Facebook.
, ,
.

276

3. - -

, ,
.
, :
//
$now = time();
while (file_exists($upload_filename = $upload_dir . $now .
'-' .
$_FILES[$image_fieldname]['name'])) {
$now++;
}

, , .
1. $now
, PHP- time.
2. while. true, . ,
true, .
3. while $upload_filename:
$upload_dir , (-) . () (
$_FILES[$image_fieldname]['name']).
4. while
file_exists. ,
while. , (
, ).
5. .
while ,
, $now
.
PHP:
. ,
.
:
// ,
@move_uploaded_file($_FILES[$image_fieldname]['tmp_name'], $upload_filename)
or handle_error(" " .
" .",
", " .
" {$upload_filename}");

8.

277

,
, .
. , create_user.php, , ,
. -
. -,
, , .8.6. ( ,
, .
, -
. , . , -
-, .)

. 8.6. -

,
, . -, , - .
create_user.php .
echo :
//
$now = time();
while (file_exists($upload_filename = $upload_dir . $now .
'-' .
$_FILES[$image_fieldname]['name'])) {
$now++;
}
echo $upload_filename;
echo "<br />";
echo $_FILES[$image_fieldname]['tmp_name'];

278

3. - -

, echo :
// ,
//
//header("Location: show_user.php?user_id=" . mysql_insert_id());

, , echo, , , . .8.7.

. 8.7. echo

(-!)
, ,
- (.8.8).

. 8.8.

8.

279



, -
.
:
$insert_sql = "INSERT INTO users (first_name, last_name, email, " .
"bio, facebook_url, twitter_handle) " .
"VALUES ('{$first_name}', '{$last_name}', '{$email}', " .
" '{$bio}', " . '{$facebook_url}', " .
"'{$twitter_handle}');";
//
mysql_query($insert_sql);


,
. ALTER, :
ALTER TABLE users
ADD user_pic_path varchar(200);

. ,
users
DESCRIBE:
mysql> describe users;
+----------------+--------------+------+-----+---------+----------------+
| Field
| Type
| Null | Key | Default | Extra
|
+----------------+--------------+------+-----+---------+----------------+
| user_id
| int(11)
|
| PRI | NULL
| auto_increment |
| first_name
| varchar(20) |
|
|
|
|
| last_name
| varchar(30) |
|
|
|
|
| email
| varchar(50) |
|
|
|
|
| facebook_url
| varchar(100) | YES |
| NULL
|
|
| twitter_handle | varchar(20) | YES |
| NULL
|
|
| bio
| text
| YES |
| NULL
|
|
| user_pic_path | varchar(200) | YES |
| NULL
|
|
+----------------+--------------+------+-----+---------+----------------+
8 rows in set (0.00 sec)

user_pic_path ,
, .

, ,
, , .

280

3. - -


INSERT:
$insert_sql = "INSERT INTO users (first_name, last_name, email, " .
"bio, facebook_url, twitter_handle, " .
"user_profile_pic) " .
"VALUES ('{$first_name}', '{$last_name}', '{$email}', " .
" '{$bio}', " . '{$facebook_url}', " .
"'{$twitter_handle}', '{$upload_filename}');";
//
mysql_query($insert_sql);

. , . HTML .


, ?
PHP-,
, users, show_user.php.
? SQL MySQL.
. SQL
. SELECT , :
SELECT user_pic_path
FROM users
WHERE last_name = 'Roday';

:
mysql> select user_pic_path from users where last_name = 'Roday';
+------------------------------------+
| user_pic_path
|
+------------------------------------+
| /yellowtagmedia_com/phpMM/uploads/profile_pics/1312127661-City_2_0_by_pince-l3d.jpg |
+------------------------------------+
1 row in set (0.00 sec)

-, .
,
.

8.

281

- ,
create_user.php. ,
, :
<?php
require_once '../scripts/app_config.php';
require_once '../scripts/database_connection.php';
$upload_dir = SITE_ROOT . "uploads/profile_pics/";
$image_fieldname = "user_pic";
// PHP-
$php_errors = array(1 => ' . , php.ini',
2 => ' . , HTML',
3 => ' ',
4 => ' .');
$first_name = trim($_REQUEST['first_name']);
$last_name = trim($_REQUEST['last_name']);
$email = trim($_REQUEST['email']);
$bio = trim($_REQUEST['bio']);
$facebook_url = str_replace("facebook.org", "facebook.com", trim($_
REQUEST['facebook_url']));
$position = strpos($facebook_url, "facebook.com");
if ($position === false) {
$facebook_url = "http://www.facebook.com/" . $facebook_url;
}
$twitter_handle = trim($_REQUEST['twitter_handle']);
$twitter_url = "http://www.twitter.com/";
$position = strpos($twitter_handle, "@");
if ($position === false) {
$twitter_url = $twitter_url . $twitter_handle;
} else {
$twitter_url = $twitter_url .
substr($twitter_handle, $position + 1);
}
//
($_FILES[$image_fieldname]['error'] == 0)
or handle_error(" .",
$php_errors[$_FILES[$image_fieldname]['error']]);
// ?
@is_uploaded_file($_FILES[$image_fieldname]['tmp_name'])
or handle_error(" . !",

282

3. - -

" : " .
"'{$_FILES[$image_fieldname]['tmp_name']}'");
// ?
@getimagesize($_FILES[$image_fieldname]['tmp_name'])
or handle_error(" , " .
" .",
"{$_FILES[$image_fieldname]['tmp_name']} " .
" .");
//
$now = time();
while (file_exists($upload_filename = $upload_dir . $now .
'-' .
$_FILES[$image_fieldname]['name'])) {
$now++;
}
// ,
@move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],
$upload_filename)
or handle_error(" " .
" .",
", " .
" {$upload_filename}");
$insert_sql = "INSERT INTO users (first_name, last_name, email, " .
"bio, facebook_url, twitter_handle, user_pic_path) " .
"VALUES ('{$first_name}', '{$last_name}', '{$email}', " .
"'{$bio}', '{$facebook_url}', '{$twitter_handle}', " .
"'{$upload_filename}');";
//
mysql_query($insert_sql);
// ,
//
header("Location: show_user.php?user_id=" . mysql_insert_id());
exit();
?>

, ,
. , , ,
- , ,
.

8.

283

show_user.php create_user.html create_


user.php. show_user.php users .

require
require_once, app_config.php , ,
scripts/, . , HTML,
show_user.php, CSS JavaScript.

SELECT

. ,
SELECT, :
// SELECT
$select_query = "SELECT * FROM users WHERE user_id = " . $user_id;

,
,
SQL- INSERT:
if ($result) {
$row = mysql_fetch_array($result);
$first_name
= $row['first_name'];
$last_name
= $row['last_name'];
$bio
= preg_replace("/[\r\n]+/", "</p><p>", $row['bio']);
$email
= $row['email'];
$facebook_url = $row['facebook_url'];
$twitter_handle = $row['twitter_handle'];
$user_image
= $row['user_pic_path'];
// $twitter_handle URL
$twitter_url = "http://www.twitter.com/" .
substr($twitter_handle, $position + 1);
} else {
handle_error(" " .
" .",
" ID {$user_id}");
}

die else if
handle_error.

, :
//
$user_image = "../../images/missing_user.png";

284

3. - -

, HTML

- , $user_image:
<div id="content">
<div class="user_profile">
<h1><?php echo "{$first_name} {$last_name}"; ?></h1>
<p><img src="<?php echo $user_image; ?>" class="user_pic" />
<!-- . ... -->

. show_user.php
ID

create_user.php
. .

8.9. .

. 8.9.

, ,
( ,
, )
Firebug
-

8.

285

.
.
, , , ,
.8.10.

. 8.10.

HTML img .

HTML
- ? -?

. , ... ?


URL-
, , -,
, -. -
. ,
.

HTML ,
public_html/.

show_user.php test.php.
PHP
:
<?php
echo " : {$_SERVER['DOCUMENT_ROOT']}";
?>

286

3. - -

$_SERVER ,
PHP. DOCUMENT_ROOT
.

, $_SERVER, www.php.net/manual/
ru/reserved.variables.server.php.

.
, , .8.11.
/home1/b/bmclaugh/yellowtagmedia_com. ,
/ /home1/b/bmclaugh/
yellowtagmedia_com.

. 8.11.

: , . ,
.
, yellowtagmedia_com ( ,
).
, .
, ,
test.php:
<?php
echo " : {$_SERVER['DOCUMENT_ROOT']}";
$image_sample_path =
"/home1/b/bmclaugh/yellowtagmedia_com/phpMM/" .
"uploads/profile_pics/1312128274-james_roday.jpg";
?>

str_replace,
. ,
, , :
<?php
echo " : {$_SERVER['DOCUMENT_ROOT']}";

8.

287

$image_sample_path =
"/home1/b/bmclaugh/yellowtagmedia_com/phpMM/" .
"uploads/profile_pics/1312128274-james_roday.jpg";
$web_image_path = str_replace($_SERVER['DOCUMENT_ROOT'],
'', $image_sample_path);
?>

, echo:
<?php
echo " : {$_SERVER['DOCUMENT_ROOT']}";
$image_sample_path =
"/home1/b/bmclaugh/yellowtagmedia_com/phpMM/" .
"uploads/profile_pics/1312128274-james_roday.jpg";
$web_image_path = str_replace($_SERVER['DOCUMENT_ROOT'],
'', $image_sample_path);
echo "<br /><br /> : {$web_image_path}";
?>

test.php. , , , .8.12.

. 8.12. , :
, ,

,
. Enter, ,
, , .
.8.13.
test.php ... :
. app_config.php
test.php:
function get_web_path($file_system_path) {
return str_replace($_SERVER['DOCUMENT_ROOT'], '', $file_system_path);
}

288

3. - -

. 8.13. ,
,

, ? , .
1. function , , app_config.php.
2. : get_web_path.
3. , : $file_system_path.
- , .
4. $file_system_path, ('').
5. return
str_replace.
return.
PHP
, : - ,
. /usr/bbentley/web/
images/profile.jpg /usr/bbentley/web,
get_web_path /images/profile.jpg.

8.

289


, , , Ruby on Rails,
. ,
-, .
, PHP . ,
test.php ,
.
, ,
- -
, CSS,
.
, HTML .
,
.

. , , . , , ../../../web/images/profile.jpg,
. , ,
, . ,
.


:
show_
user.php. .
, , :
if ($result) {
$row = mysql_fetch_array($result);
$first_name
= $row['first_name'];
$last_name
= $row['last_name'];
$bio
= preg_replace("/[\r\n]+/", "</p><p>", $row['bio']);
$email
= $row['email'];
$facebook_url = $row['facebook_url'];
$twitter_handle = $row['twitter_handle'];

290
$user_image

3. - -

= get_web_path($row['user_pic_path']);

// $twitter_handle URL
$twitter_url = "http://www.twitter.com/" .
substr($twitter_handle, $position + 1);
} else {
handle_error(" " .
" .",
" ID {$user_id}");
}

. ( create_user.php), show_user.php
user_id URL.
show_user.php :
(.8.14).

. 8.14. , , , ,
, ,

8.

291


app_config.php
: $_SERVER['DOCUMENT_ROOT'],
: get_web_path.
,
app_config.php. :
//
define("SITE_ROOT", "/phpMM/");

SITE_ROOT , , . ,
- ,
. , /,
.

. ,
, .
-
. , /home1/b/bmclaugh/
yellowtagmedia_com. /, /phpMM,
, , .
, -, $_SERVER['DOCUMENT_ROOT'].
, get_web_path
, -
. , SITE_ROOT /phpMM,
- :
//
define("SITE_ROOT", $_SERVER['DOCUMENT_ROOT'] . "/phpMM/");

-
-
. , , /home1/b/bmclaugh/
yellowtagmedia_com/phpMM. , . , ,
,
get_web_path.
, , handle_error.
:
function handle_error($user_error_message, $system_error_message) {
header("Location: " . SITE_ROOT . "scripts/show_error.php" .
"?error_message={$user_error_message}" .
"&system_error_message={$system_error_message}");
}

292

3. - -

?
get_web_path ,
, . -, :
? ,

.
.
. ,
, PHP Ruby, Perl PHP, ,
,
. ,
, .
?
. , , , !
,
. .
, ,
/. ,
. . ,
,
.
, .
,
.
SITE_ROOT ,
. ,
, .
, SITE_ROOT . :
function handle_error($user_error_message, $system_error_message) {
header("Location: " . get_web_path(SITE_ROOT) .
"scripts/show_error.php" .
"?error_message={$user_error_message}" .
"&system_error_message={$system_error_message}");
}

8.

293


. , -, . , ,
,
. .


, .

.
URL-,
- . ,
,
show_user.php.
?
, -, . -?
, - - .
,
10 20 , , 1 2? , .
,
- -. ,
, : , .
, . . ,
. , ,
.


. -
.
. , ,
, , ,
.
.
, ,
PHP
- , .
, PHP .
, ?
. ,
, ,
.
, .

, .
: users, . ,
SELECT- INSERT-, .
, .

users. : .

, , URL

- Facebook

Twitter .
, users .

9.

295


, , ,
. .
,
, .
,
images,
, , .

, users.
( ),
, Twitter.
, ,
.

ID . ,
user_id users. users.
. -

, ,
.
MIME-. - -

: JPG, GIF, PNG ..


. .
. , -

.
SQL CREATE:
CREATE TABLE images (
image_id
int
filename
varchar(200)
mime_type
varchar(50)
file_size
int
image_data mediumblob
);

AUTO_INCREMENT PRIMARY KEY,


NOT NULL,
NOT NULL,
NOT NULL,
NOT NULL

:
mediumblob. - -1:
tinyblob 256;
blob 65 blob-;
1

(Blob,
Binary

Large

Object
) . , , : , , .

296

3. - -

mediumblob 16 ;
longblob - 4 longblob-


, -
. ,
longblob. ,
, ,
.
longblob
. ,
, longblob, 2,
, mediumblob, 2. longblob ,

.
,
2, mediumblob.
, ,
.
,
varchar(255), . - .
longblob, ( ) ,
, mediumblob.
, ,
users. :
mysql> USE bmclaugh;
Database changed
mysql> SHOW tables;
+------------------------------------+
| Tables_in_bmclaugh
|
+------------------------------------+
| images
|
| users
|
+------------------------------------+
2 rows in set (0.00 sec)

9.

297

create_user.php.
, . ,
, ,
, PHP
( getimagesize).
,
. images, , .
create_user.php ,
.

create_user.php.
create_user.php.bak - ,
.

<?php
require_once '../scripts/app_config.php';
require_once '../scripts/database_connection.php';
// , ,
$upload_dir = SITE_ROOT . "uploads/profile_pics/";
$image_fieldname = "user_pic";
// PHP-
$php_errors = array(1 => ' . , php.ini',
2 => ' . , HTML',
3 => ' ',
4 => ' .');
$first_name = trim($_REQUEST['first_name']);
$last_name = trim($_REQUEST['last_name']);
$email = trim($_REQUEST['email']);
$bio = trim($_REQUEST['bio']);
$facebook_url = str_replace("facebook.org", "facebook.com", trim($_
REQUEST['facebook_url']));
$position = strpos($facebook_url, "facebook.com");
if ($position === false) {
$facebook_url = "http://www.facebook.com/" . $facebook_url;
}
$twitter_handle = trim($_REQUEST['twitter_handle']);
$twitter_url = "http://www.twitter.com/";
$position = strpos($twitter_handle, "@");

298

3. - -

if ($position === false) {


$twitter_url = $twitter_url . $twitter_handle;
} else {
$twitter_url = $twitter_url .
substr($twitter_handle, $position + 1);
}
//
($_FILES[$image_fieldname]['error'] == 0)
or handle_error(" .",
$php_errors[$_FILES[$image_fieldname]['error']]);
// ?
@is_uploaded_file($_FILES[$image_fieldname]['tmp_name'])
or handle_error(" . !",
" : " .
"'{$_FILES[$image_fieldname]['tmp_name']}'");
// ?
@getimagesize($_FILES[$image_fieldname]['tmp_name'])
or handle_error(" , " .
" .",
"{$_FILES[$image_fieldname]['tmp_name']} " .
" .");
//
$now = time();
while (file_exists($upload_filename = $upload_dir . $now .
'-' .
$_FILES[$image_fieldname]['name'])) {
$now++;
}
// , move_uploaded_file
//
//
$insert_sql = "INSERT INTO users (first_name, last_name, email, " .
"bio, facebook_url, twitter_handle) " .
"VALUES ('{$first_name}', '{$last_name}', '{$email}', " .
"'{$bio}', '{$facebook_url}', '{$twitter_handle}');";
//
mysql_query($insert_sql);
// ,
//
header("Location: show_user.php?user_id=" . mysql_insert_id());
exit();
?>

9.

299

, .
, INSERT,
users, images.
:
, images
$_FILES ( ).
:
$insert_sql = "INSERT INTO users (first_name, last_name, email, " .
"bio, facebook_url, twitter_handle) " .
"VALUES ('{$first_name}', '{$last_name}', '{$email}', " .
"'{$bio}', '{$facebook_url}', '{$twitter_handle}');";
//
mysql_query($insert_sql);
// images
$image = $_FILES[$image_fieldname];
$image_filename = $image['name'];
$image_info = getimagesize($image['tmp_name']);
$image_mime_type = $image_info['mime'];
$image_size = $image['size'];
$image_data = file_get_contents($image['tmp_name']);
$insert_image_sql = "INSERT INTO images " .
"(filename, mime_type, file_size, image_data) " .
"VALUES ('{$image_filename}', '{$image_mime_type}', " .
"'{$image_size}', '{$image_data}');";
mysql_query($insert_image_sql);
// ,
//
header("Location: show_user.php?user_id=" . mysql_insert_id());
?>

, ,
.
$image:
$image = $_FILES[$image_fieldname];

.
$_FILES[$image_fieldname].
, .
:
$image_filename = $image['name'];

300

3. - -

getimagesize

. getimagesize -
, ,
MIME
- ( ), , HTML- ( ).
, :
$image_size = getimagesize($image['tmp_name']);

: getimagesize , ,
, , , .
MIME-:
$image_info = getimagesize($image['tmp_name']);
$image_mime_type = $image_info['mime'];

- .
, :
$image_size = $image['size'];

file_get_contents

, getimagesize.
, ,
file_get_contents. , , , image_data
images:
$image_data = file_get_contents($image['tmp_name']);


INSERT
, ,
INSERT :
$insert_image_sql = "INSERT INTO images " .
"(filename, mime_type, file_size, image_data) " .
"VALUES ('{$image_filename}', '{$image_mime_type}', " .
"'{$image_size}', '{$image_data}');";
mysql_query($insert_image_sql);

9.

301

! , .
MySQL. ,
- .



, , ,
.
, PHP MySQL.
, .
.

, , , - PHP. . 4 5 PHP
,
getimagesize, mysql_real_escape_string,
.

mysql_real_escape_string
, . , $image_data, mysql_real_escape_string
mysql_query INSERT. , MySQL:
$insert_sql = "INSERT INTO users (first_name, last_name, email, " .
"bio, facebook_url, twitter_handle) " .
"VALUES ('{mysql_real_escape_string($first_name)}', " .
"'{mysql_real_escape_string($last_name)}', " .
"'{mysql_real_escape_string($email)}', " .
"'{mysql_real_escape_string($bio)}', " .
"'{mysql_real_escape_string($facebook_url)}', " .
"'{mysql_real_escape_string($twitter_handle)}');";
//
mysql_query($insert_sql);
// images
$image = $_FILES[$image_fieldname];
$image_filename = $image['name'];
$image_info = getimagesize($image['tmp_name']);
$image_mime_type = $image_info['mime'];
$image_size = $image['size'];

302

3. - -

$image_data = file_get_contents($image['tmp_name']);
$insert_image_sql = "INSERT INTO images " .
"(filename, mime_type, file_size, image_data) " .
"VALUES ('{mysql_real_escape_string($image_filename)}', ".
"'{mysql_real_escape_string($image_mime_type)}', " .
"'{ mysql_real_escape_string($image_size)}', " .
"'{mysql_real_escape_string($image_data)}');";
mysql_query($insert_image_sql);

$image_size ,
mysql_real_escape_string. ,
,
.
.
, . ,
PHP ,
, ,
.


. , , ( "{$variable}"
$variable), PHP
- . mysql_real_escape_string.
.
: mysql_real_escape_string
:
// images
$image = $_FILES[$image_fieldname];
$image_filename = mysql_real_escape_string($image['name']);
$image_info = getimagesize($image['tmp_name']);
$image_mime_type = mysql_real_escape_string($image_info['mime']);
// ....

, . :
MySQL. $image_filename
- ,
, MySQL?
,
mysql_real_escape_string -

9.

303

SQL- INSERT.
MIME- , ,
, ,
MySQL.
, , , SQL,
. PHP-
sprintf, . ,
sprintf. ,
, mysql_query.
, .
,
, , .
,

%s:
$hello = sprintf("Hello there, %s %s", $first_name, $last_name);
echo $hello;

, ($first_name) John ($last_name)


Wayne.
:
Hello there, John Wayne

sprintf %s , , $first_name.
%s , ,
$last_name. , $hello.
sprintf sprintf.
:
$hello = sprintf("Hello there, %s", $first_name . ' ' . $last_name);
echo $hello;

, sprintf, mysql_real_escape_string:
// $insert_sql
$insert_sql = sprintf("INSERT INTO users " .
"(first_name, last_name, email, " .
"bio, facebook_url, twitter_handle) " .
"VALUES ('%s', '%s', '%s', '%s', '%s', '%s');",
mysql_real_escape_string($first_name),
mysql_real_escape_string($last_name),

304

3. - -

mysql_real_escape_string($email),
mysql_real_escape_string($bio),
mysql_real_escape_string($facebook_url),
mysql_real_escape_string($twitter_handle));
//
mysql_query($insert_sql);


, , ,
.
images:
$insert_image_sql = sprintf("INSERT INTO images " .
"(filename, mime_type, " .
"file_size, image_data) " .
"VALUES ('%s', '%s', %d, '%s');",
mysql_real_escape_string($image_filename),
mysql_real_escape_string($image_mime_type),
mysql_real_escape_string($image_size),
mysql_real_escape_string($image_data));
mysql_query($insert_image_sql);

, %d sprintf:
, ,
1024 92048. , INSERT
, .

sprintf
PHP- sprintf
, ,
mysql_real_escape_string
. ,
: sprintf
.
,


. ,
(, , ,
- ), ,
, , SQL-.
sprintf . - SQL-, .

9.

305

. create_user.php,
,
. create_user.php
show_user.php.
, . images
:
mysql> SELECT image_id, filename FROM images;
+----------+----------------------------+
| image_id | filename
|
+----------+----------------------------+
|
4 | 220px-William_Shatner.jpeg |
+----------+----------------------------+
1 row in set (0.00 sec)

SELECT *,

MySQL
, !
,
.

PhpMyAdmin
, ,
images (.

9.1). PhpMyAdmin

- - BLOB .
, 11729,
-, 11,5.
: , .

. 9.1. PhpMyAdmin

ID

, . , .9.2.

306

3. - -

. 9.2. -

,
, .
?
- ,
. create_
user.php:
// $insert_sql
$insert_sql = sprintf("INSERT INTO users " .
"(first_name, last_name, email, " .
"bio, facebook_url, twitter_handle) " .
"VALUES ('%s', '%s', '%s', '%s', '%s', '%s');",
mysql_real_escape_string($first_name),
mysql_real_escape_string($last_name),
mysql_real_escape_string($email),
mysql_real_escape_string($bio),
mysql_real_escape_string($facebook_url),
mysql_real_escape_string($twitter_handle));
//
mysql_query($insert_sql);
$insert_image_sql = sprintf("INSERT INTO images " .
"(filename, mime_type, " .

9.

307

"file_size, image_data) " .


"VALUES ('%s', '%s', %d, '%s');",
mysql_real_escape_string($image_filename),
mysql_real_escape_string($image_mime_type),
mysql_real_escape_string($image_size),
mysql_real_escape_string($image_data));
mysql_query($insert_image_sql);
// ,
//
header("Location: show_user.php?user_id=" . mysql_insert_id());

? . , mysql_insert_id ID INSERT,
INSERT users, INSERT
images. , show_user.php ,
ID , .
:
// $insert_sql
$insert_sql = sprintf("INSERT INTO users " .
"(first_name, last_name, email, " .
"bio, facebook_url, twitter_handle) " .
"VALUES ('%s', '%s', '%s', '%s', '%s', '%s');",
mysql_real_escape_string($first_name),
mysql_real_escape_string($last_name),
mysql_real_escape_string($email),
mysql_real_escape_string($bio),
mysql_real_escape_string($facebook_url),
mysql_real_escape_string($twitter_handle));
//
mysql_query($insert_sql);
$user_id = mysql_insert_id();
$insert_image_sql = sprintf("INSERT INTO images " .
"(filename, mime_type, " .
"file_size, image_data) " .
"VALUES ('%s', '%s', %d, '%s');",
mysql_real_escape_string($image_filename),
mysql_real_escape_string($image_mime_type),
mysql_real_escape_string($image_size),
mysql_real_escape_string($image_data));
mysql_query($insert_image_sql);
// ,
//
header("Location: show_user.php?user_id=" . $user_id);
exit();

308

3. - -

,
: show_user.php,
(.9.3).

. 9.3.

, , - . ,
,
INSERT.
, ,
.


. users images,
.
show_user.php ,
images users?
, - .
ID users (user_id)
images (image_id), . ?

9.

309

,
, : ? , ,
, ?
? ? . , ( 11).
. ,
users, image_id
.
:
mysql> ALTER TABLE users
->
ADD profile_pic_id int;
Query OK, 6 rows affected (0.11 sec)
Records: 6 Duplicates: 0 Warnings: 0


, . ALTER
.
. .
, .
, , , ,
. ,
, .
PHP MySQL
. ,
.


profile_pic_id , .
,
images.
,
, ,
FOREIGN KEY .
, profile_pic_id ID, image_id images. MySQL .
MySQL ,
MySQL InnoDB.
, - InnoDB.
, MySQL ,

310

3. - -

. InnoDB
, :
ALTER TABLE [table-name]
ENGINE = InnoDB;

Google MySQL foreign keys, .


, InnoDB, .
[----]_id. ,
, users images,
, image
images _id. image_id.
users profile_pic_id?
images . ,
. ,
, , ,
.
image_id users
. , , , , , . ,
profile_pic_id users, , , company_logo_id companies, , ? profile_pic_id,
, ( pic - ) (
profile ).


, .
images, ID
profile_pic_id users.
users images:
// $insert_sql
$insert_sql = sprintf("INSERT INTO users " .
"(first_name, last_name, email, " .
"bio, facebook_url, twitter_handle) " .
"VALUES ('%s', '%s', '%s', '%s', '%s', '%s');",
mysql_real_escape_string($first_name),
mysql_real_escape_string($last_name),

9.

311

mysql_real_escape_string($email),
mysql_real_escape_string($bio),
mysql_real_escape_string($facebook_url),
mysql_real_escape_string($twitter_handle));
//
mysql_query($insert_sql);
$user_id = mysql_insert_id();
$insert_image_sql = sprintf("INSERT INTO images " .
"(filename, mime_type, " .
"file_size, image_data) " .
"VALUES ('%s', '%s', %d, '%s');",
mysql_real_escape_string($image_filename),
mysql_real_escape_string($image_mime_type),
mysql_real_escape_string($image_size),
mysql_real_escape_string($image_data));
mysql_query($insert_image_sql);
// ,
//
header("Location: show_user.php?user_id=" . $user_id);
exit();

ID , mysql_insert_id,
. ID

, mysql_insert_id . ,
profile_pic_id users. ,

.
1. INSERT users.
2. INSERT images.
3. UPDATE ID users.
, .
. ,
,
, .

MySQL .
1. INSERT images (
ID ).
2. INSERT users
ID ,
INSERT.

312

3. - -

? MySQL
, , .
! , .
INSERT:
//
$insert_image_sql = sprintf("INSERT INTO images " .
"(filename, mime_type, " .
"file_size, image_data) " .
"VALUES ('%s', '%s', %d, '%s');",
mysql_real_escape_string($image_filename),
mysql_real_escape_string($image_mime_type),
mysql_real_escape_string($image_size),
mysql_real_escape_string($image_data));
mysql_query($insert_image_sql);
// $insert_sql
$insert_sql = sprintf("INSERT INTO users " .
"(first_name, last_name, email, " .
"bio, facebook_url, twitter_handle) " .
"VALUES ('%s', '%s', '%s', '%s', '%s', '%s');",
mysql_real_escape_string($first_name),
mysql_real_escape_string($last_name),
mysql_real_escape_string($email),
mysql_real_escape_string($bio),
mysql_real_escape_string($facebook_url),
mysql_real_escape_string($twitter_handle));
//
mysql_query($insert_sql);
// ,
//
header("Location: show_user.php?user_id=" . $user_id);
exit();

- .
mysql_query, ,
, , .
. , users
, mysql_insert_id.

ID INSERT, , INSERT,
users. ,
: mysql_insert_id ID ,

9.

313

images, INSERT
users.
//
$insert_image_sql = sprintf("INSERT INTO images " .
"(filename, mime_type, " .
"file_size, image_data) " .
"VALUES ('%s', '%s', %d, '%s');",
mysql_real_escape_string($image_filename),
mysql_real_escape_string($image_mime_type),
mysql_real_escape_string($image_size),
mysql_real_escape_string($image_data));
mysql_query($insert_image_sql);
// $insert_sql
$insert_sql = sprintf("INSERT INTO users " .
"(first_name, last_name, email, " .
"bio, facebook_url, twitter_handle, " .
"profile_pic_id) " .
"VALUES ('%s', '%s', '%s', '%s', '%s', '%s', %d);",
mysql_real_escape_string($first_name),
mysql_real_escape_string($last_name),
mysql_real_escape_string($email),
mysql_real_escape_string($bio),
mysql_real_escape_string($facebook_url),
mysql_real_escape_string($twitter_handle),
mysql_insert_id());
//
mysql_query($insert_sql);
// ,
//
header("Location: show_user.php?user_id=" . mysql_insert_id());
exit();

, , ID , profile_pic_id,
, , sprintf %d
.

. create_user.php :
<?php
require_once '../scripts/app_config.php';
require_once '../scripts/database_connection.php';
$upload_dir = SITE_ROOT . "uploads/profile_pics/";

314

3. - -

$image_fieldname = "user_pic";
// PHP-
$php_errors = array(1 => ' . , php.ini',
2 => ' . , HTML',
3 => ' ',
4 => ' .');
$first_name = trim($_REQUEST['first_name']);
$last_name = trim($_REQUEST['last_name']);
$email = trim($_REQUEST['email']);
$bio = trim($_REQUEST['bio']);
$facebook_url = str_replace("facebook.org", "facebook.com", trim($_
REQUEST['facebook_url']));
$position = strpos($facebook_url, "facebook.com");
if ($position === false) {
$facebook_url = "http://www.facebook.com/" . $facebook_url;
}
$twitter_handle = trim($_REQUEST['twitter_handle']);
$twitter_url = "http://www.twitter.com/";
$position = strpos($twitter_handle, "@");
if ($position === false) {
$twitter_url = $twitter_url . $twitter_handle;
} else {
$twitter_url = $twitter_url . substr($twitter_handle, $position + 1);
}
//
($_FILES[$image_fieldname]['error'] == 0)
or handle_error(" .",
$php_errors[$_FILES[$image_fieldname]['error']]);
// ?
@is_uploaded_file($_FILES[$image_fieldname]['tmp_name'])
or handle_error(" . !",
" : " .
"'{$_FILES[$image_fieldname]['tmp_name']}'");
// ?
@getimagesize($_FILES[$image_fieldname]['tmp_name'])
or handle_error(" , " .
" .",
"{$_FILES[$image_fieldname]['tmp_name']} " .
" .");
//

9.

$now = time();
while (file_exists($upload_filename = $upload_dir . $now .
'-' .
$_FILES[$image_fieldname]['name'])) {
$now++;
}
// images
$image = $_FILES[$image_fieldname];
$image_filename = $image['name'];
$image_info = getimagesize($image['tmp_name']);
$image_mime_type = $image_info['mime'];
$image_size = $image['size'];
$image_data = file_get_contents($image['tmp_name']);
$insert_image_sql = sprintf("INSERT INTO images " .
"(filename, mime_type, file_size, image_data) " .
"VALUES ('%s', '%s', %d, '%s');",
mysql_real_escape_string($image_filename),
mysql_real_escape_string($image_mime_type),
mysql_real_escape_string($image_size),
mysql_real_escape_string($image_data));
mysql_query($insert_image_sql);
$insert_sql = sprintf("INSERT INTO users " .
"(first_name, last_name, email, " .
"bio, facebook_url, twitter_handle, " .
"profile_pic_id) " .
"VALUES ('%s', '%s', '%s', '%s', '%s', '%s', %d);",
mysql_real_escape_string($first_name),
mysql_real_escape_string($last_name),
mysql_real_escape_string($email),
mysql_real_escape_string($bio),
mysql_real_escape_string($facebook_url),
mysql_real_escape_string($twitter_handle),
mysql_insert_id());
//
mysql_query($insert_sql);
// ,
//
header("Location: show_user.php?user_id=" . mysql_insert_id());
exit();
?>

315

316

3. - -

. , ID
images:
mysql> select image_id from images;
+----------+
| image_id |
+----------+
|
4 |
|
5 |
|
6 |
+----------+
3 rows in set (0.00 sec)

, ID,
, users:
mysql> select user_id, first_name, last_name, profile_pic_id from users;
+---------+------------+-----------+----------------+
| user_id | first_name | last_name | profile_pic_id |
+---------+------------+-----------+----------------+
|
1 | C. J.
| Wilson
|
NULL |
|
5 | Peter
| Gabriel
|
NULL |
|
7 | Bob
| Jones
|
NULL |
|
22 | James
| Roday
|
NULL |
|
30 | William
| Shatner
|
6 |
+---------+------------+-----------+----------------+
7 rows in set (0.01 sec)

! , ID
users
.

WHERE
? ID
. :
$select_query = sprintf("SELECT * FROM users WHERE user_id = %d",
$user_id);

sprintf- show_user.php.
show_user.php.
, profile_
pic_id . ,
:
if ($result) {
$row = mysql_fetch_array($result);
$first_name
= $row['first_name'];
$last_name
= $row['last_name'];

9.

$bio
$email
$facebook_url
$twitter_handle
$profile_pic_id

=
=
=
=
=

317

preg_replace("/[\r\n]+/", "</p><p>", $row['bio']);


$row['email'];
$row['facebook_url'];
$row['twitter_handle'];
$row['profile_pic_id'];

$image_query = sprintf("SELECT * FROM images WHERE image_id = %d",


$profile_pic_id);
$image_result = mysql_query($image_query);
// $twitter_handle URL
$twitter_url = "http://www.twitter.com/" .
substr($twitter_handle, $position + 1);
}

show_user.php ,
,
.

, , .
:
profile_pic_id users image_id images.


:
WHERE.
, users
images, profile_pic_id
image_id :
SELECT first_name, last_name, filename
FROM users, images
WHERE profile_pic_id = image_id;

MySQL
:
mysql> SELECT first_name, last_name, filename
->
FROM users, images
-> WHERE profile_pic_id = image_id;
+------------+-----------+----------------------------+
| first_name | last_name | filename
|
+------------+-----------+----------------------------+
| William
| Shatner
| 220px-William_Shatner.jpeg |
+------------+-----------+----------------------------+
1 row in set (0.02 sec)

William Shatner,
.

318

3. - -

! .
. .

( )
, -
. :
SELECT first_name, last_name, filename
FROM users, images
WHERE profile_pic_id = image_id;

, first_name last_name users.


, , filename. (, - ,
, filename images.)
profile_pic_id image_id. ,
?
,
. :
SELECT users.first_name, users.last_name, images.filename
FROM users, images
WHERE users.profile_pic_id = images.image_id;

, . : .
- ,
. SQL

. , -
, :
SELECT u.first_name, u.last_name, i.filename
FROM users u, images i
WHERE u.profile_pic_id = i.image_id;

,
,
.


. , ?

9.

319

, ,
.

, - : , . . , ,
.


, .
show_user.php.
,
.
show_image.php.
,
:
<?php
require '../scripts/app_config.php';
require '../scripts/database_connection.php';
?>


, . .
1. ID .
2. SELECT- images, ID .
3. SELECT- .
4. , .
5. , .
6. , .
7. .
, , , , .
,
.
1. , ID .
2. , ID images.
3. ,
.

320

3. - -

.
, .

ID
ID

. : ID, .
<?php
require '../scripts/app_config.php';
require '../scripts/database_connection.php';
if (!isset($_REQUEST['image_id'])) {
handle_error(" .");
}
$image_id = $_REQUEST['image_id'];
?>

, show_
user.php. - handle_error
.

SELECT-

SQL
- sprintf, mysql_query.
<?php
// require
// ID
// SELECT
$select_query = sprintf("SELECT * FROM images WHERE image_id = %d",
$image_id);
//
$result = mysql_query($select_query);
?>

, , .

,

$result . . ,
:

9.

321

if ($return_rows) {
// ,
echo "<p>, :</p>";
echo "<ul>";
while ($row = mysql_fetch_row($result)) {
echo "<li>{$row[0]}</li>";
}
echo "</ul>";
} else {
// . , .
echo "<p> :</p>";
echo "<p>{$query_text}</p>";
}

5. ,
.

if, :
if ($result) {
$row = mysql_fetch_array($result);
//
} else {
handle_error(" " .
" .",
" ID {$user_id}");
}

, $result true , .
, , ,
SQL
- .
show_image.php - .
if-:
<?php
// require
// ID
//
if (mysql_num_rows($result) == 0) {
handle_error(" .",
" ID" . $image_id . ".");
}
$image = mysql_fetch_array($result);
?>

322

3. - -

,
. (
, .)



.
. , , ,
. , ,
.
,
.
( if-), , , . -
. ,
-
.
show_
user.php:
if ($result) {
$row = mysql_fetch_array($result);
//
} else {
handle_error(
" " .
" .",
" ID
{$user_id}");
}

, . ?
- . , .
, . ?
?
, , , , . , ,
. ,
, , . ,
.
show_image.php,
, ,
. .

9.

323


, ,
. , , ,
.
HTML
, - .
.
.
MIME- text/html text/xml, image/jpeg, image/
gif image/png.
,
( ). ,
.
,
, . :
header("Location: " . SITE_ROOT . "scripts/show_error.php?" .
error_message={$user_error_message}&" .
system_error_message={$system_error_message}");

. ,
Location. ,
URL, , Location
URL, .
, header
PHP
, .
, ( ), :
Content-type , MIME-
;
Content-length ,
, .

images, mime_type file_size.
, ,
show_image.php:
<?php
//
//
//
//

require
ID

header('Content-type: ' . $image['mime_type']);


header('Content-length: ' . $image['file_size']);
?>

324

3. - -

(
image/jpeg image/gif). ,


? :
<?php
//
//
//
//
//

require
ID


echo $image['image_data'];
?>

, , - images . . ,

. : ,
.


, :
1. ID .
2. SELECT- images ID .
3. SELECT- .
4. , .
5. , .
6. , .
7. .
. , .
.
.
1. , ID .
2. , ID images.
3. ,
.

9.

325

. , ? , , ,
Content-type? Content-length? ?
- ? , - , , , ?
.
, ,
, .
, . :
-, ,
.... handle_error.
PHP try-catch.
try try-catch , ,
. : . catch try-catch
. - try
- , catch .
, catch Exception.
, , ,
, , , handle_error.
show_image.php, ,
, try :
<?php
require '../scripts/app_config.php';
require '../scripts/database_connection.php';
try {
if (!isset($_REQUEST['image_id'])) {
handle_error(" .");
}
$image_id = $_REQUEST['image_id'];
// SELECT
$select_query = sprintf("SELECT * FROM images WHERE image_id = %d",
$image_id);
//
$result = mysql_query($select_query);
if (mysql_num_rows($result) == 0) {

326

3. - -

handle_error(" .",
" ID " . $image_id . ".");
}
$image = mysql_fetch_array($result);
header('Content-type: ' . $image['mime_type']);
header('Content-length: ' . $image['file_size']);
echo $image['image_data'];

}
?>

. - , PHP
Exception (), , catch:
<?php
require '../scripts/app_config.php';
require '../scripts/database_connection.php';
try {
// ,
} catch (Exception exc) {
}
?>

, : catch, Exception. exc


, ,
.

exc $, PHP $
. PHP ,
, exc , ,
.

, catch - :
<?php
require '../scripts/app_config.php';
require '../scripts/database_connection.php';
try {
// ,
} catch (Exception exc) {
handle_error(" .",
" : " . $exc->getMessage());
}
?>

9.

327

, ,
, ->. , handle_error. , handle_error , ,
.
exc getMessage. PHP ,
. ->.

, .
, ,
.

, ,
, PHP try.
show_image.php :
<?php
require '../scripts/app_config.php';
require '../scripts/database_connection.php';
try {
if (!isset($_REQUEST['image_id'])) {
handle_error(" .");
}
$image_id = $_REQUEST['image_id'];
// SELECT
$select_query = sprintf("SELECT * FROM images WHERE image_id = %d",
$image_id);
//
$result = mysql_query($select_query);
if (mysql_num_rows($result) == 0) {
handle_error(" .",
" ID " . $image_id . ".");
}
$image = mysql_fetch_array($result);
header('Content-type: ' . $image['mime_type']);
header('Content-length: ' . $image['file_size']);
echo $image['image_data'];
} catch (Exception $exc) {
handle_error(" .",
" : " . $exc->getMessage());
}
?>

328

3. - -

, ? , .

,
MySQL .
, ID:
mysql> select image_id, filename from images;
+----------+----------------------------+
| image_id | filename
|
+----------+----------------------------+
|
6 | 220px-William_Shatner.jpeg |
+----------+----------------------------+
1 row in set (0.03 sec)

URL show_image.php.
Enter! , , , ,
. 9.4, ID.

. 9.4. ID

URL : show_image.php?image_id=6.
( ),
, .9.5.

9.

329

. 9.5.

:
.
- -
. .
,
, .

,

, show_user.php. ,
show_image.php . ,
, . ,
, ,
. , , . , show_user.php .


, , SQL-,
images users:
SELECT u.first_name, u.last_name, i.filename
FROM users u, images i
WHERE u.profile_pic_id = i.image_id;

330

3. - -

? , , , show_
image.php, ID , users profile_pic_id. users images.
SQL-
ID :
<?php
require '../scripts/app_config.php';
require '../scripts/database_connection.php';
// ID
// SELECT
//
if ($result) {
$row = mysql_fetch_array($result);
$first_name
= $row['first_name'];
$last_name
= $row['last_name'];
$bio
= preg_replace("/[\r\n]+/", "</p><p>", $row['bio']);
$email
= $row['email'];
$facebook_url
= $row['facebook_url'];
$twitter_handle = $row['twitter_handle'];
$image_id
= $row['profile_pic_id'];
// $twitter_handle URL
} else {
handle_error(" .",
" ID {$user_id}");
}
?>
<!-- HTML -->

, URL ,
users .


(src)
, .
, , ,
.
HTML- img:
<img src="/images/roday.jpg" />

img , .
src , .

9.

331


/images/roday.jpg. ? , roday.jpg.
, roday.jpg URL, .
, ,
. , src , ,
. , , ,
.
:
<img src="show_image.php?image_id=6" />

show_image.php
ID
, ,
img.
HTML,
:
<?php
// PHP-
?>
<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"></div>
<div id="content">
<div class="user_profile">
<h1><?php echo "{$first_name} {$last_name}"; ?></h1>
<p><img src="show_image.php?image_id=<?php echo $image_id; ?>"
class="user_pic" />
<?php echo $bio; ?></p>
<p class="contact_info">
<?php echo $first_name; ?>:
</p>
<ul>
<!-- -->
</ul>
</div>
</div>
<div id="footer"></div>
</body>
</html>

332

3. - -

! src img ID.


, show_user.php, :
<?php
require '../scripts/app_config.php';
require '../scripts/database_connection.php';
// ID
$user_id = $_REQUEST['user_id'];
// SELECT
$select_query = sprintf("SELECT * FROM users WHERE user_id = %d",
$user_id);
//
$result = mysql_query($select_query);
if ($result) {
$row = mysql_fetch_array($result);
$first_name
= $row['first_name'];
$last_name
= $row['last_name'];
$bio
= preg_replace("/[\r\n]+/", "</p><p>", $row['bio']);
$email
= $row['email'];
$facebook_url
= $row['facebook_url'];
$twitter_handle = $row['twitter_handle'];
$image_id
= $row['profile_pic_id'];
// $twitter_handle URL
$twitter_url = "http://www.twitter.com/" .
substr($twitter_handle, $position + 1);
} else {
handle_error(" .",
" ID {$user_id}");
}
?>
<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"></div>
<div id="content">
<div class="user_profile">
<h1><?php echo "{$first_name} {$last_name}"; ?></h1>

9.

<p><img src="show_image.php?image_id=<?php echo $image_id; ?>"


class="user_pic" />
<?php echo $bio; ?></p>
<p class="contact_info">
<?php echo $first_name; ?>:
</p>
<ul>
<li>...
<a href="<?php echo $email; ?>"><?php echo $email; ?></a></li>
<li>...
<a href="<?php echo $facebook_url; ?>">
Facebook </a></li>
<li>... <a href="<?php echo $twitter_url; ?>">
Twitter</a></li>
</ul>
</div>
</div>
<div id="footer"></div>
</body>
</html>

.9.6.

. 9.6.

333

334

3. - -

. , , ,
?

-
?
, , , ,
Google. , 20 30
PHP, , .
, !
PHP,
, ? ,
,
.
-, , , . , ,
, , , , , .
, , , , .
, ,
, . ,
,
.
-, -
, . ,
, . , JPG, GIF, , , HTML,
.
,
? , -
, , .
,
.

9.

335

, ?
,
, (
). ,
, , ,
PHP. : ?
: .
: . , . , ,
,
, , .
, ?
-? ,
?
? - ?
.
: ,
. .
, , ,
. , (, !) ,
.

,
...
- , ,
. ,
, ,
, . SELECT images image_data .
, 100,
1. 100 ,
.

. ,
? ,

336

3. - -

, , ,
.

?
,
, . (, ,
!) , ,
. ?
-, .
, -
- ,
.
-, profile_pic_id
users. SQL, :
ALTER TABLE users
DROP COLUMN profile_pic_id;

images:
DROP TABLE images;

. .

10

: ,
, .
. PHP MySQL, , ,
PHP: ,
, . -
, .
. . ? ,
, - , , ,
MySQL. , , , . ,
, , -
MySQL.
. , , .

. .
-. - .
, -,
, Facebook, Twitter
Google+. ,
. SQL-,
PHP
MySQL

HTML

, . DELETE WHERE.

338

3. - -

,
.
, , .
,
MySQL ?
,
.

,
? , :
, . ,
, HTML,
, Photoshop.
,
:
, ;
;
;
;
, .

, , ,
, ( ).
.

,
-
,
. show_user.php , , .
. ,
, . , ,
, , .
, ,
, , .
. ,

10. ,

339


. ,
.
, ? .10.1 . , - . ,
, . .
, .
: .

. 10.1.

HTML
- , PHP:
<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"></div>
<div id="content">
<ul>

340

3. - -

<li>
<a href="show_user.php?user_id=30"> </a>
(<a href="mailto:bill@williamshatner.com">bill@williamshatner.com</a>)
<a href="delete_user.php?user_id=30">
<img class="delete_user" src="../images/delete.png" width="15" />
</a>
</li>
<li>
<a href="show_user.php?user_id=22"> </a>
(<a href="mailto:james@roday.net">james@roday.net</a>)
<a href="delete_user.php?user_id=22">
<img class="delete_user" src="../images/delete.png" width="15" />
</a>
</li>
<li>
<a href="show_user.php?user_id=1">. . </a>
(<a href="mailto:cj@texasrangers.com">cj@texasrangers.com</a>)
<a href="delete_user.php?user_id=1">
<img class="delete_user" src="../images/delete.png" width="15" />
</a>
</li>
</ul>
</div>
<div id="footer"></div>
</body>
</html>


. , ,
, , , , . , , ?
, ?
, .
,
Photoshop
. , HTML
CSS , Photoshop,
.
. -,
, - . -,
, , , .
.
? , .

10. ,

341

, (
) - iPad iPhone,
, .
. ,
, , , ,
,
.
.
,

, , .
, -

.
, -

.
,
. ,
,
, , .

, ,
,
, . .
.


: , , . SQL, ,
. , , :
SELECT *
FROM users;

342

3. - -

. , , ,
PHP MySQL. :
.

SELECT (
)
SELECT * , . , ,
. , users,
. , SELECT *:
mysql> describe users;
+----------------+--------------+------+-----+---------+----------------+
| Field
| Type
| Null | Key | Default | Extra
|
+----------------+--------------+------+-----+---------+----------------+
| user_id
| int(11)
|
| PRI | NULL
| auto_increment |
| first_name
| varchar(20) |
|
|
|
|
| last_name
| varchar(30) |
|
|
|
|
| email
| varchar(50) |
|
|
|
|
| facebook_url
| varchar(100) | YES |
| NULL
|
|
| twitter_handle | varchar(20) | YES |
| NULL
|
|
| bio
| text
| YES |
| NULL
|
|
| user_pic_path | varchar(200) | YES |
| NULL
|
|
| profile_pic_id | int(11)
| YES |
| NULL
|
|
+----------------+--------------+------+-----+---------+----------------+
9 rows in set (0.10 sec)

, ,
user_pic_path profile_pic_id. ,
,
images, .
:
ALTER TABLE users
DROP COLUMN profile_pic_id;

.10.1. ,
first_name, last_name user_id show_user.php, email
. , SELECT * : facebook_url, twitter_handle, bio user_pic_path.
? :
.

10. ,

343

users . ,
. ,
100, 1000 10000, ,
, 20. ,
* ( , bio) users, .
, ? :
SELECT user_id, first_name, last_name, email
FROM users;

. SELECT.

, ?
. , user_pic_path
users . , ,
SELECT?
, SELECT, , . ,
, ,
- ? , .
,
.
, , ,
. , , . , . ,
-
. .
SELECT * , , .
, , , .
SELECT. .
.

344

3. - -

: -

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



, SELECT.
. ,
: ? , admin.
php, ?
:
create_user.php ;
show_user.php ;
app_config.php ;
database_connection.php .

. , ,
. , create_user.php
, , ,
show_user.php.
admin.php?
,
? ,
admin.php.
. ,
.
, .
, ,
show_users.php.
, , show_users.php
, :

10. ,

345

<?php
require_once '../scripts/app_config.php';
require_once '../scripts/database_connection.php';
// SELECT
$select_users =
"SELECT user_id, first_name, last_name, email " .
" FROM users";
//
$result = mysql_query($select_users);
?>

SELECT , sprintf.
.

HTML-: ,
:
<?php
//
?>
<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"></div>
<div id="content">
<ul>
<!-- <li>- -->
</ul>
</div>
<div id="footer"></div>
</body>
</html>

,
PHP HTML. .10.2
, ,
show_users.php.

346

3. - -

,
!

. 10.2. ,
SELECT


<li> .
HTML , sprintf:
$user_row = sprintf(
"<li><a href='show_user.php?user_id=%d'>%s %s</a> " .
"(<a href='mailto:%s'>%s</a>) " .
"<a href='delete_user.php?user_id=%d'><img " .
"class='delete_user' src='../images/delete.png' " .
"width='15' /></a></li>",
//
);

sprintf
. sprintf,
,
.
.

,
:
<li><a href='show_user.php?user_id=1'>.. </a>
(<a href='mailto:cj@texasrangers.com'>cj@texasrangers.com</a>)

10. ,

347

<a href='delete_user.php?user_id=1'><img class='delete_user'


src='../images/delete.png' width='15' /></a></li>

. , , :
while ($row = mysql_fetch_row($result)) {
echo "<li>{$row[0]}</li>";
}

, ,
, :
while ($row = mysql_fetch_row($result)) {
echo "<li>{$row['col_name']}</li>";
}

$row, col_name.
users , , HTML, :
<?php
//
?>
<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"></div>
<div id="content">
<ul>
<?php
while ($user = mysql_fetch_array($result)) {
$user_row = sprintf(
"<li><a href='show_user.php?user_id=%d'>%s %s</a> " .
"(<a href='mailto:%s'>%s</a>) " .
"<a href='delete_user.php?user_id=%d'><img " .
"class='delete_user' src='../images/delete.png' " .
"width='15' /></a></li>",
$user['user_id'], $user['first_name'], $user['last_name'],
$user['email'], $user['email'], $user['user_id']);
echo $user_row;
}
?>
</ul>
</div>
<div id="footer"></div>
</body>
</html>

348

3. - -

HTML , : delete_user.php. ,
. ,
.

sprintf
- .
,
HTML
, . ,
.

HTML

- .
PHP, , ,
echo . , PHP- , -
PHP- . , , PHP- HTML,
.
show_users.php. PHP-,
HTML... - PHP,
HTML.
, , , HTML,
PHP, ,
, . , , HTML PHP.
, PHP:
.
, (, - )
, . -
HTML PHP . .

PHP , .
, , . show_users.php , , ,
. .10.3 , .
,
. , show_user.php,
(.10.4).

10. ,

349

. 10.3.

. 10.4. show_user.php,

, , , ,
, , . PHP- ,

350

3. - -

. ,
PHP
-,
HTML
- . , Wordpress 100% PHP.


, , . , , , .
,
, .
,
.
.


?
:
DELETE FROM users;

,
WHERE:
DELETE FROM users
WHERE user_id = [id__];

. user_id
, . show_users.php:
<?php
while ($user = mysql_fetch_array($result)) {
$user_row = sprintf(
"<li><a href='show_user.php?user_id=%d'>%s %s</a> " .
"(<a href='mailto:%s'>%s</a>) " .
"<a href='delete_user.php?user_id=%d'><img " .
"class='delete_user' src='../images/delete.png' " .
"width='15' /></a></li>",
$user['user_id'], $user['first_name'], $user['last_name'],
$user['email'], $user['email'], $user['user_id']);
echo $user_row;
}
?>

10. ,

351

HTML,
:
<a href='delete_user.php?user_id=22'>...</a>

, , user_id show_user.php:
// ,
//
header("Location: show_user.php?user_id=" . mysql_insert_id());

create_user.php.
, .

, user_id ,
show_users.php,
SELECT ,
. !


. delete_user.php,
:
<?php
require_once '../scripts/app_config.php';
require_once '../scripts/database_connection.php';
//
$user_id = $_REQUEST['user_id'];
// DELETE
$delete_query = sprintf("DELETE FROM users WHERE user_id = %d",
$user_id);
//
mysql_query($delete_query);
// show_users
// ( )
header("Location: show_users.php");
exit();
?>

352

3. - -


, . app_config.php. ,
- ,
.
,
, , :
! ,
, , . ? .
, . ,
. , , , ,
, , , .
, , , , ,
emacs vi ,
- . .
? ,
, .
, .
$insert_sql, $insert_query.
, PHP , . ,
.
(, )
.
yy , . , .
yy ,
.
.
yy (.10.5)
(.10.6) , ,
, .
.
yy . , ,
.

10. ,

353

. 10.5. ,
,

. 10.6.
,
( Terminal Mac)

!
. .

354

3. - -

. show_users.php , .
, , .10.7.
, .10.3,
.

. 10.7.



.
, , , delete_user.php, show_users.php.

, .
. ,
. , .
.
. - - ? , ,
: ?,
!
!, .
.

10. ,

355

. ,
.
, delete_user.php. show_users.php.

JavaScript
, ,
. , , - PHP, .
, PHP-,
HTML

- , , OK.
, -
.
Ajax,
. ,
JavaScript
,
.
show_users.php
JavaScript:
<?php
// SELECT
?>
<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function delete_user(user_id) {
if (confirm(" , ?" +
"\n !")) {
window.location = "delete_user.php?user_id=" + user_id;
}
}
</script>
</head>
<body>
<!-- HTML -->
</body>
</html>

. , , delete_user.php .

356

3. - -

, , user_id
, delete_user.php JavaScript window.location.

, JavaScript.
- ,
, JavaScript, .

, ?
, , , . .
, , , ,
. (, , - ?)
? :
<head>
<link href="../css/phpMM.css"
rel="stylesheet" type="text/css"
/>
<script type="text/javascript">
function delete_user(user_id) {
//
}
</script>
</head>

, , JavaScript
head- .
.
1. JavaScript-.
2. JavaScript-.
3. , JavaScript
!
4. , JavaScript, .
, . , www.amazon.com, www.google.com www.apple.com.
- <script>- head-
!

10. ,

357

, , , Apple, Amazon Google?


, . , ,
JavaScript. , .
,
jQuery ( )
,
. ,
CSS-,
app_config.php database_connection.php.
JavaScript- delete_user
! , , , . ,
, ,
!
JavaScript head-
, . ,
JavaScript- p-
td-. JavaScript . ,
.


JavaScript :
, delete_user.php,
JavaScript:
<?php
while ($user = mysql_fetch_array($result)) {
$user_row = sprintf(
"<li><a href='show_user.php?user_id=%d'>%s %s</a> " .
"(<a href='mailto:%s'>%s</a>) " .
"<a href='javascript:delete_user(%d);'><img " .
"class='delete_user' src='../images/delete.png' " .
"width='15' /></a></li>",
$user['user_id'], $user['first_name'], $user['last_name'],
$user['email'], $user['email'], $user['user_id']);
echo $user_row;
}
?>

358

3. - -

! , - .10.8 , ,
, .

. 10.8.


.
- .
. ,
, .
, , SELECT, , delete_user.php
. , ,
show_users.php. .
. , .
, . , , , -

10. ,

359

. ,
.
1. , show_users.php.
2. .
3. delete_user.php .
4. , :
, , , .
5. show_users.php , .
, 4,
.



, , delete_user.php.

show_users.php, .
, , , ,
. delete_user.php:
header("Location: show_users.php");


PHP

HTTP
. , Location. HTTP-
URL. , .
, , header
, PHP

- . echo, HTML, - .
, . ,
- header, header, . ,
, , ,
Location exit(),
- .
, , delete_user.php,
PHP, - .

360

3. - -

, ,
show_users.php. ,
show_users.php
.

-- ( - )
-.
MVC, Model-View-Controller (--).
: , . MVC,
.
, . , , .
delete_user.php MySQL .
MVC- PHP-, User.php, ,
delete() remove(). :
User user_to_delete =
User.find_by_id($user_id);
user_to_delete.delete();

, MVC ,
. , ,

.
, .
show_user.php show_users.php . HTML . ,
, , .
MVC- .
.
, , . delete_user.php. , ,
, , , show_users.php.
-, PHP,
MVC-. , PHP, MVC-,
. ,
, delete_user.php ( ), show_users.php ().

10. ,

361

delete_user.php (
). show_users.php

, , ,
.
PHP MVC-, ? . -,
MVC,
- MVC , ,
. -,
, ,
, .
delete_user.php, , .
, , show_users.php, .
, delete_user.php ,
, ,
- .
. , success_message:
// show_users,
// ( )
$msg = " .";
header("Location: show_users.php?success_message={$msg}");

, error_message,
.

, ,
show_users.php, .
show_users.php, ,
, show_users.
php. success_message ,
(.10.9).
. , ,
delete_user.php
URL
, , : ,
. :
, .

362

3. - -

. 10.9.

,
JavaScript
show_users.php, .

. show_users.php
, .
( - ) .

? ,
JavaScript .
, , ,
.

, JavaScript
JavaScript,
show_users.php. JavaScript
,
. -,
window.location.href, URL
:
function get_request_param_value(param_name) {
param_name = param_name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]" + param_name + "=([^&#]*)";
var regex = new RegExp(regexS);

10. ,

363

var results = regex.exec(unescape(window.location.href));


if (results == null)
return "";
else
return results[1];

.
, JavaScript.
, ,
, .
, ,
PHP, JavaScript.

,
success_message (, JavaScript-):
msg = get_request_param_value("success_message");
if (msg.length > 0) {
//
}

,
, get_request_param_value,
:
msg = get_request_param_value("success_message")
if (msg.length > 0) {
alert(msg);
}

. , head- show_users.php script-, , .10.10.

. 10.10.

364

3. - -

.10.10 , alert. ,
, alert
, . window.onload,
onload, body, jQuery
,
.

,
, .

PHP
, JavaScript,
, : , ,
, , HTML,
CSS JavaScript, .
JavaScript , success_message.
URL ,
.
, show_users.php ,
, . , HTML
JavaScript, , ,
, , , ,
.
show_users.php, :
$msg = $_REQUEST['success_message'];

JavaScript:
function get_request_param_value(param_name) {
param_name = param_name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]" + param_name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(unescape(window.location.href));
if (results == null)
return "";
else
return results[1];
}

, , get_request_param_value
JavaScript PHP,
.

: ,
. ,
.

10. ,

365

, PHP :
// ,
if (isset($_REQUEST['success_message'])) {
$msg = $_REQUEST['success_message'];
}

. . ( ), JavaScript HTML-:
<script type="text/javascript">
function delete_user(user_id) {
if (confirm(" , ?" +
"\n !")) {
window.location = "delete_user.php?user_id=" + user_id;
}
}
<?php if (isset($msg)) { ?>
window.onload = function() {
alert("<?php echo $msg ?>");
}
<?php } ?>
</script>

, , show_
users.php:
<?php
require_once '../scripts/app_config.php';
require_once '../scripts/database_connection.php';
// SELECT
$select_users =
"SELECT user_id, first_name, last_name, email " .
" FROM users";
//
$result = mysql_query($select_users);
// ,
if (isset($_REQUEST['success_message'])) {
$msg = $_REQUEST['success_message'];
}
?>
<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function delete_user(user_id) {
if (confirm(" , ?" +
"\n !")) {

366

3. - -

window.location = "delete_user.php?user_id=" + user_id;

<?php if (isset($msg)) { ?>


window.onload = function() {
alert("<?php echo $msg ?>");
}
<?php } ?>
</script>
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"></div>
<div id="content">
<ul>
<?php
while ($user = mysql_fetch_array($result)) {
$user_row = sprintf(
"<li><a href='show_user.php?user_id=%d'>%s %s</a> " .
"(<a href='mailto:%s'>%s</a>) " .
"<a href='javascript:delete_user(%d);'><img " .
"class='delete_user' src='../images/delete.png' " .
"width='15' /></a></li>",
$user['user_id'], $user['first_name'], $user['last_name'],
$user['email'], $user['email'], $user['user_id']);
echo $user_row;
}
?>
</ul>
</div>
<div id="footer"></div>
</body>
</html>

, show_user.php
show_users.php, app_config.php. , -
, -,
,
. ,
, .

, ,
PHP

.
PHP
, . , , ,
.
. -
URL, yellowtagmedia.com/phpMM/
ch10/show_users.php?success_message=%20%20%20,

10. ,

367

,
show_users.php. , URL
(.10.11).

. 10.11.

, ,
. .

10.12 , .
URL , , HTML .

. 10.12.

368

3. - -

show_users.php URL-
. ,
JavaScript HTML-, show_users.php.
.10.13 : window.onload
.

. 10.13.

: ? URL (

URL
), URL . ,
, , -
. , ,
.

alert
, .
OK , ,
. .
, - , , -.
: ?

10. ,

369

, UX ( user
experience, ) UI (user interface, ).
, UX
, UI.
: .
, , ,
- -.

, .
jQuery,
, , ,
. :
, .


jQuery, jQuery
- www.jqueryui.com/demos/dialog. ,
Modal-. jQueryUI 10,
5 ,
jQuery.

? , ,
, . ,
OK? ,
, .
-, , , .
, .
:
? !


, , , :
,
? ,
handle_error? - ,
- : , , .

?
11, ? .

370

3. - -

: - ,
.
, ,
JavaScript, .

. ,
5 10 . - , :
<body>
<?php display_messages($_REQUEST); ?>
<!-- , HTML- -->
</body>

, . , , (.10.14).

. 10.14. ,
- -

HTML
:
<div id="messages">
<div class="success">

10. ,

371

<p> </p>
</div>
</div>

,
.10.15.

. 10.15.

, , create_user.html.
c HTML , ,
. ,
. , ,
.

HTML .
,
class div-:
<div id="messages">
<div class="error">
<p> </p>
</div>
</div>

372

3. - -

. ,
delete_user.php
show_users.php, ,
.
, - :
<div id="messages">
<div class="success">
<p>$msg</p>
</div>
</div>

, , PHP.
:
<div id="messages">
<div class="success">
<p><?php echo $msg; ?></p>
</div>
</div>

. , :
function display_success_message($msg) {
echo "<div id='messages'>\n";
echo " <div class='success'>\n";
echo " <p>{$msg}</p>\n";
echo " </div>\n";
echo "</div>\n\n";
}

sprintf? , \n?
, display_success_message ,
.
sprintf. echo ( echo sprintf). HTML, PHP <?php ?>.
.
\n. ,
. :
<div id='messages'> <div class='success'>
<p>{$msg}</p> </div></div>

10. ,

373

HTML. . HTML .
HTML:
<div id='messages'>
<div class='success'>
<p>{$msg}</p>
</div>
</div>

, \n? - . ?
. . ? echo, sprintf ?
PHP- , - , . sprintf
. echo
sprintf . , , , .
\n . , HTML- ,
. ,
, , . ( - ,
, .)
, . ?
:
function display_error_message($msg) {
echo "<div id='messages'>\n";
echo " <div class=error>\n";
echo " <p>{$msg}</p>\n";
echo " </div>\n";
echo "</div>\n\n";
}

div- messages.
. -, .

,
:
function display_messages($success_msg, $error_msg) {
echo "<div id='messages'>\n";
display_success_message($success_msg);

374

3. - -

display_error_message($error_msg);
echo "</div>\n\n";
}
function display_success_message($msg) {
echo " <div class='success'>\n";
echo " <p>{$msg}</p>\n";
echo " </div>\n";
}
function display_error_message($msg) {
echo " <div class='error'>\n";
echo " <p>{$msg}</p>\n";
echo " </div>\n";
}

. ... ?
?

, . , :
function display_success_message($msg) {
echo " <div class='success'>\n";
echo " <p>{$msg}</p>\n";
echo " </div>\n";
}
function display_error_message($msg) {
echo " <div class='error'>\n";
echo " <p>{$msg}</p>\n";
echo " </div>\n";
}

. , , class div-. , .
:
function display_message($msg, $msg_type) {
echo " <div class='{#msg_type}'>\n";
echo " <p>{$msg}</p>\n";
echo " </div>\n";
}

10. ,

375

. , , , DRY-.
:
define("SUCCESS_MESSAGE", "success");
define("ERROR_MESSAGE", "error");
function display_messages($success_msg, $error_msg) {
echo "<div id='messages'>\n";
display_message($success_msg, SUCCESS_MESSAGE);
display_message($error_msg, ERROR_MESSAGE);
echo "</div>\n\n";
}
function display_message($msg, $msg_type) {
echo " <div class='{#msg_type}'>\n";
echo " <p>{$msg}</p>\n";
echo " </div>\n";
}

DRY-
, , DRY- , (Drying up your code,
). DRY, Dont Repeat Yourself, : .
. 4, , ,
app_config.php?
( ) . ,
.
database_connection.php.

.
DRY-: DRY-
, .
display_success_message display_error_message,
.
, ?
, . ,
, .
, DRY-
, .

376

3. - -

! ,
: ERROR, error, errors - .
.
. view.php. require_once app_config.php:
<?php
require_once 'app_config.php';
define("SUCCESS_MESSAGE", "success");
define("ERROR_MESSAGE", "error");
function display_messages($success_msg, $error_msg) {
echo "<div id='messages'>\n";
display_message($success_msg, SUCCESS_MESSAGE);
display_message($error_msg, ERROR_MESSAGE);
echo "</div>\n\n";
}
function display_message($msg, $msg_type) {
echo " <div class='{$msg_type}'>\n";
echo " <p>{$msg}</p>\n";
echo " </div>\n";
}
?>

app_config.php view.php . ,
, ,
, . ,
require_once , .

View Display

view.php.
scripts/ , app_config.php database_
connection.php. , , .
display_messages display_message app_config.php,
.
, , .
, show_users.php, , , view.
php . ,

10. ,

377

, delete_user.php, ,
view.php . .

, database_connection.php.
, require_once database_connection.php .
- , . ,
.

,

, . show_
users.php ,
, view.php:
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function delete_user(user_id) {
if (confirm(" , ?" +
"\n !")) {
window.location = "delete_user.php?user_id=" + user_id;
}
}
<?php if (isset($msg)) { ?>
window.onload = function() {
alert("<?php echo $msg ?>");
}
<?php } ?>
</script>
</head>

View
. ,
require_once, :
<?php
require_once '../scripts/app_config.php';
require_once '../scripts/database_connection.php';
require_once '../scripts/view.php';
// ....
?>

378

3. - -

. , . ?
? , !
, show_users.php PHP-,
head- HTML- .

display_messages HTML:
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"></div>
<?php display_messages($msg); ?>

: display_messages : .
, - ,
display_messages ,
.
,
HTML-. , HTML
. ?
! ,
, HTML...

JavaScript
, show_users.php:
<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function delete_user(user_id) {
if (confirm(" , ?" +
"\n !")) {
window.location = "delete_user.php?user_id=" + user_id;
}
}
</script>
</head>

body, ( ) . .
, ,

. view.php .


, , . view.php.
display_messages
, ,

10. ,

379

. - , div-, , .
( display_header),
head- HTML . JavaScript, head- ,
,
JavaScript .
( display_title),
, ,
, - ,
.
,
.


display_messages
view.php, , display_messages
. PHP
NULL,
.

NULL , .
Ruby nil. Java null. PHP NULL, C++.
: .

, NULL ,
. PHP
:
if ($value == NULL) // -


is_null. is_null - , PHP ,
.
display_messages.
(NULL), , display_message
:
function display_messages($success_msg, $error_msg) {
echo "<div id='messages'>\n";
if (!is_null($success_msg)) {
display_message($success_msg, SUCCESS_MESSAGE);
}
if (!is_null($error_msg)) {
display_message($error_msg, ERROR_MESSAGE);
}
echo "</div>\n\n";
}

380

3. - -

. :
, show_users.php, ,
$error_msg? $success_msg?
display_messages . , , .

:
function do_something(this_value = "default value") {
// - this_value
}

, display_messages NULL
:
function display_messages($success_msg = NULL, $error_msg = NULL) {
echo "<div id='messages'>\n";
if (!is_null($success_msg)) {
display_message($success_msg, SUCCESS_MESSAGE);
}
if (!is_null($error_msg)) {
display_message($error_msg, ERROR_MESSAGE);
}
echo "</div>\n\n";
}

display_messages -
, view.php.


heredoc
?
HTML
- . html, title, head
JavaScript, .
view.php, ,
, , .
. ,
JavaScript head-, ,
:
function display_head($page_title = "", $embedded_javascript = NULL) {

$page_title.
, . -, , ,
HTML- .
echo JavaScript:
function display_head($page_title = "", $embedded_javascript = NULL) {
echo "<html>";

10. ,

381

echo " <head>";


echo " <title>{$page_title}</title>";
echo ' <link href="../css/phpMM.css" rel="stylesheet" type="text/css" />';
if (!is_null($embedded_javascript)) {
echo "<script type='text/javascript'>" .
$embedded_javascript .
"</script>";
}
echo " </head>";

, link
HTML, href,
rel type. , ,
, \" \'.
, .
,
: , .
? ,
. ,
PHP .
PHP, .
, heredoc ( ). heredoc ,
. ,
, ,
- .
heredoc ,
,
:
$some_text = <<<EOD

, : , ,
EOD.

. EOD EOT, ,
.

,
. , ,
{$var_name}. :
<html>
<head>
<title>{$page_title}</title>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>

382

3. - -

, :
EOD;

, :
$some_text = <<<EOD
<html>
<head>
<title>{$page_title}</title>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
EOD;

.
, .
.
,
.

unexpected T_SL. , , PHP
, :
.

, display_head :
function display_head($page_title = "", $embedded_javascript = NULL) {
echo <<<EOD
<html>
<head>
<title>{$page_title}</title>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
EOD;
if (!is_null($embedded_javascript)) {
echo "<script type='text/javascript'>" .
$embedded_javascript .
"</script>";
}
echo " </head>";
}

, , , display_head , heredoc

. ,
. echo,
heredoc, JavaScript.
, .

10. ,

383

()
display_head

. show_users.php (
show_user.php) HTML

.
HTML
, , display_head.
, heredoc, show_users.php,
JavaScript:
<?php
//
?>
<?php
$delete_user_script = <<<EOD
function delete_user(user_id) {
if (confirm(" , ?" +
" !")) {
window.location = "delete_user.php?user_id=" + user_id;
}
}
EOD;
display_head("", $delete_user_script);
?>
<!-- HTML- -->
</html>

PHP, , <?php/?> (
, display_head). .
, , , ,
<?php. .

heredoc ,
JavaScript, display_head,
. heredoc
, sprintf.
HTML
.
.
, show_users.php.
- , .10.16.
, , , ,

384

3. - -

. 10.16. show_users.php

. view.php, HTML.
, ... display_head.


View
. display_
messages, HTML, .
, display_head HTML
JavaScript

, HTML

, ( ), . ,
, :
<html>
<head>
<title></title>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
<script type='text/javascript'>function delete_user(user_id) {
if (confirm(" , ?" +
" !")) {
window.location = "delete_user.php?user_id=" + user_id;
}
}</script>

10. ,

385

</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"></div>
<div id='messages'>
<div class='success'>
<p> .</p>
</div>
</div>
<div id="content">
<!-- HTML- -->
</div>
</body>
</html>

. view.php display_
title:
function display_title($title, $success_msg = NULL, $error_msg = NULL) {
echo <<<EOD
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example">$title</div>
EOD;
display_messages($success_msg, $error_msg); ?>
}

, ? , , show_users.php
:
display_title("", $msg);

, :
$_REQUEST.
, ? ,
NULL:
display_title("",
$_REQUEST['success_message'], $_REQUEST['error_message']);

show_users.php , success_message
$_REQUEST,
display_title.

. display_head display_title
, display_head .
display_title
.

386

3. - -

$_REQUEST display_title?
,
$_REQUEST display_title. display_title
$_REQUEST['success_message'] $_REQUEST['error_message']. .
,
, , ,
.
, (
view.php, HTML) . ,
,
.
, MVC- PHP .
,
.
view.php
$_REQUEST.


, display_
title , body - HTML-. , ,
:
HTML display_title HTML- display_head;
, display_head, , , , display_title.

HTML HTML display_head


, ?
:
<?php
// -
?>
<?php display_head($title, $javascript);
<?php display_title($title,

?>

10. ,

387

$_REQUEST['success_message'], $_REQUEST['error_message']);

?>

<!-- HTML -->


</html>

? ? ?
<?php
// -
?>
<?php page_start($title, $javascript,
$_REQUEST['success_message'], $_REQUEST['error_message']) ?>
<!-- HTML -->
</html>

,
$title.
HTML-.
display_title, display_head display_
messages. , :
function page_start($title, $javascript = NULL,
$success_message = NULL, $error_message = NULL) {

display_head($title, $javascript);
display_title($title, $success_message, $error_message);

view.php ,
.

! .



? display_head, display_title
.

. 380 PHP
.

388

3. - -


show_users.php. .

,
heredoc
, :
<?php
require_once '../scripts/app_config.php';
require_once '../scripts/database_connection.php';
require_once '../scripts/view.php';
// SELECT
$select_users =
"SELECT user_id, first_name, last_name, email " .
" FROM users";
//
$result = mysql_query($select_users);
//
$delete_user_script = <<<EOD
function delete_user(user_id) {
if (confirm(" , ?" +
" !")) {
window.location = "delete_user.php?user_id=" + user_id;
}
}
EOD;
page_start("Current Users", $delete_user_script,
$_REQUEST['success_message'], $_REQUEST['error_message']);
?>
<div id="content">
<ul>
<?php
while ($user = mysql_fetch_array($result)) {
$user_row = sprintf(
"<li><a href='show_user.php?user_id=%d'>%s %s</a> " .
"(<a href='mailto:%s'>%s</a>) " .
"<a href='javascript:delete_user(%d);'><img " .
"class='delete_user' src='../images/delete.png' " .
"width='15' /></a></li>",
$user['user_id'], $user['first_name'], $user['last_name'],
$user['email'], $user['email'], $user['user_id']);
echo $user_row;
}
?>
</ul>
</div>
<div id="footer"></div>
</body>
</html>

10. ,

389

. ,
.
, page_start.
- view.php. ,
page_end, div- , footer, - . , .
, .
.

-

.
HTML view.php, database_
connection.php, . ,
,
require_once. : -
, .
,
. .
, . , 20 30
?
, .
,
.
, . :
display_page($title, $javascript, $content);

:
display_head($title, $javascript);
display_messages($msg);
display_content($content);
display_footer();

,
. ,
, .

390

3. - -

- , , .
, display_page,
? display_head,
display_messages, display_content, ...
? , .
,
- .
,
,
.
. , , ,
.

11.
12. Cookie-,

13.

11

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

, , delete_user.php admin.php.

? , ,
; , -, . . delete_user.php

- , create_user.html,
.
! show_users.php, -,
, ,
. , ,
.
.
, , - , .
,
, .

11.

393

( ).
( , -

).
(,
create_user.html, ).
,

.
, -

(, ).
-

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

. , ,
. ,
, , , .

, .
. , YouTube Google,
, , ,
Twitter
Facebook

. , , .
.


, ,
. , .

394

4.

.
(, , .
, create_user.html.)


HTTP-
,
HTTP
-, - HTTP. .
:
function handle_error($user_error_message, $system_error_message) {
header("Location: " . get_web_path(SITE_ROOT) .
"scripts/show_error.php" .
"?error_message={$user_error_message}" .
"&system_error_message={$system_error_message}");
}

handle_error scripts/app_config.php.

, HTTP-, Location
. Content-type Content-length:
header('Content-type: ' . $image['mime_type']);
header('Content-length: ' . $image['file_size']);

show_image.php 9,
, .


HTTP
-. Content-type Location.
:
HTTP/1.1 401 Unauthorized

, , . 401 ,
, . 200,
, , , , 404
HTTP.

HTTP www.w3.org/Protocols/rfc2616/rfc2616sec10.html.

11.

395

, , . ?
:
WWW-Authenticate: Basic realm="The Social Site"

. ,
.
WWW-Authenticate, ,
basic. (realm), . "The Social Site". , ,
, .

...

, ,
show_users.php. :
<?php
require_once '../scripts/app_config.php';
require_once '../scripts/database_connection.php';
require_once '../scripts/view.php';
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="The Social Site"');
// SELECT
$select_users =
"SELECT user_id, first_name, last_name, email " .
" FROM users";
// PHP
?>

,
ch11. ,
, , - .

show_users.php. ,
(.11.1). ,
, . , ,
.

396

4.

. 11.1.

- .htpasswd ( - Apache), .
.htpasswd PHP.
.htpasswd
, .


. show_users.php, ,
, .
Cancel (). ? , .11.2.
, . ,
.11.2. - , ,
show_users.php, .
? , - . , . , ,
. , show_users.php.

11.

397

. 11.2. show_users.php

, , , -
. , - ,
, show_users.php. ,
.

HTTP
- , PHP ,
, . PHP
, .
$_SERVER,
:
$_SERVER['PHP_AUTH_USER'] ;
$_SERVER['PHP_AUTH_PW'] .

$_SERVER SITE_ROOT app_config.php,


get_web_path.

398

4.

, .
1.
HTTP
-, .
2.
$_SERVER['PHP_AUTH_USER'] $_SERVER['PHP_AUTH_PW'] .
3. , .
, , , ... .
.
1. .
2. ( , , ).
3. ,
.
,
- . ,
, . ,
, .
isset.
:
if (!isset($_SERVER['PHP_AUTH_USER']) ||
!isset($_SERVER['PHP_AUTH_PW'])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="The Social Site"');
}

, . - .
, ,

.


, ,
: , .
, . :
if (!isset($_SERVER['PHP_AUTH_USER']) ||
!isset($_SERVER['PHP_AUTH_PW'])) {

11.

399

header('HTTP/1.1 401 Unauthorized');


header('WWW-Authenticate: Basic realm="The Social Site"');

header:
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="The Social Site"');

, PHP

, header:
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="The Social Site"');
// ,
//

:
if (!isset($_SERVER['PHP_AUTH_USER']) ||
!isset($_SERVER['PHP_AUTH_PW'])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="The Social Site"');
exit(" ." .
" . .");
}

, ,
exit, die,
(.11.3).

. 11.3.
,


( !)
, ,
. ,
, . , . ,
while, :
while (_____) {
______();
}

400

4.

, PHP. ,
. .

, .
, , ,
.
if (!isset($_SERVER['PHP_AUTH_USER']) ||
!isset($_SERVER['PHP_AUTH_PW'])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="The Social Site"');
exit(" ." .
" . .");
}


- ,

,
. ,
, - .
. ,
, .
if, while, else, , PHP, .
:
while (_____) {
______();
}

,
PHP. , $_SERVER, ,
. , , ,
, :
while (_____) {

- :
if (($_SERVER['PHP_AUTH_USER'] !=
VALID_USERNAME) ||
($_SERVER['PHP_AUTH_PW'] !=
VALID_PASSWORD)) {

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

11.

401

, . .
. , ,
- ,
. ,
, , .
, ,
.
, , show_users.php. ,
, . :
if (!isset($_SERVER['PHP_AUTH_USER']) ||
!isset($_SERVER['PHP_AUTH_PW'])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="The Social Site"');
exit(" ." .
" . .");
} else {
if (($_SERVER['PHP_AUTH_USER'] != VALID_USERNAME) ||
($_SERVER['PHP_AUTH_PW'] != VALID_PASSWORD)) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="The Social Site"');
exit(" ." .
" . .");
}
}

if exit .
exit , ,
. , ,
.
.

- . , HTTP- .
, ,
,
. :
if (!isset($_SERVER['PHP_AUTH_USER']) ||
!isset($_SERVER['PHP_AUTH_PW']) ||
($_SERVER['PHP_AUTH_USER'] != VALID_USERNAME) ||
($_SERVER['PHP_AUTH_PW'] != VALID_PASSWORD)) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="The Social Site"');
exit(" ." .
" . .");
}

402

4.

show_users.php.

show_users.php,
if, :
<?php
require_once '../scripts/app_config.php';
require_once '../scripts/database_connection.php';
require_once '../scripts/view.php';
define(VALID_USERNAME, "admin");
define(VALID_PASSWORD, "super_secret");
if (!isset($_SERVER['PHP_AUTH_USER']) ||
!isset($_SERVER['PHP_AUTH_PW']) ||
($_SERVER['PHP_AUTH_USER'] != VALID_USERNAME) ||
($_SERVER['PHP_AUTH_PW'] != VALID_PASSWORD)) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="The Social Site"');
exit(" ." .
" . .");
}

show_users.php admin super_secret (.11.4). show_users.php (.11.5).


(..11.1).

. 11.4.
PHP $_SERVER

11.

403

. 11.5. , ;


show_users.php , . ? ,
show_users.php, , , delete_user.php. .
, ,
app_config.php database_connection.php:
,
.

: authorize.php
authorize.php.
:
<?php
define(VALID_USERNAME, "admin");
define(VALID_PASSWORD, "super_secret");
?>

404

4.

, , authorize,
get_credentials - .
? require_
once authorize.php, - ?
, ,
:
require_once "../scripts/authorize.php;"


?
, . show_users.php : . , ,
, ,
show_users.php.
, ,
, .
, ,
... . .
, , ( ).
,
,
.
, . -
PHP, authorize.php.
authorize.php ,
.
JavaScript
<script>- - :
<script type="text/javascript">
dashboard_alert("#hits_count_dialog");
$("#hits_count_dialog").dialog("open");
query_results_tables();
</script>

JavaScript, .
PHP, .
authorize.php:

11.

405

<?php
define(VALID_USERNAME, "admin");
define(VALID_PASSWORD, "super_secret");
if (!isset($_SERVER['PHP_AUTH_USER']) ||
!isset($_SERVER['PHP_AUTH_PW']) ||
($_SERVER['PHP_AUTH_USER'] != VALID_USERNAME) ||
($_SERVER['PHP_AUTH_PW'] != VALID_PASSWORD)) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="The Social Site"');
exit(" ." .
" . .");
}
?>

, require_once
authorize.php, authorize.php,
. , , .
.
show_users.php
require_once authorize.php:
<?php
require_once '../scripts/app_config.php';
require_once '../scripts/authorize.php';
require_once '../scripts/database_connection.php';
require_once '../scripts/view.php';
//
// SELECT
$select_users =
"SELECT user_id, first_name, last_name, email " .
" FROM users";
// . ...
?>

, show_users.
php, . .
delete_user.php:
<?php
require_once '../scripts/app_config.php';
require_once '../scripts/authorize.php';
require_once '../scripts/database_connection.php';
// ....

406

4.

, .
, delete_user.php. , .11.6.
,
PHP.

. 11.6. ,

! , ,
show_users.php. ,
.
. delete_
user.php, PHP authorize.php.
, The Social Site, . ,
:
header('WWW-Authenticate: Basic realm="The Social Site"');

, ,
. ,
show_users.php, , delete_user.php, ( .11.7, ).
, . ,
, .
, .
...

11.

407

. 11.7.


PHP
,
( - ). PHP ,
( app_config.php authorize.php),
. .
, , . - .
, SQL .
, . .
, , , authorize.php.

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

408

4.

:
! , .
, . , , MySQL
.

users
users.
:
mysql> describe users;
+----------------+--------------+------+-----+---------+----------------+
| Field
| Type
| Null | Key | Default | Extra
|
+----------------+--------------+------+-----+---------+----------------+
| user_id
| int(11)
| NO
| PRI | NULL
| auto_increment |
| first_name
| varchar(20) | NO
|
|
|
|
| last_name
| varchar(30) | NO
|
|
|
|
| email
| varchar(50) | NO
|
|
|
|
| facebook_url
| varchar(100) | YES |
| NULL
|
|
| twitter_handle | varchar(20) | YES |
| NULL
|
|
| bio
| text
| YES |
| NULL
|
|
| user_pic_path | text
| YES |
| NULL
|
|
+----------------+--------------+------+-----+---------+----------------+
8 rows in set (0.02 sec)

, (username) (password).
.
:
mysql> ALTER TABLE users
->
ADD username VARCHAR(32) NOT NULL
->
AFTER user_id,
->
ADD password VARCHAR(16) NOT NULL
->
AFTER username;

AFTER MySQL .
AFTER , (username password,
, ) .
, ,
DESCRIBE.

,
:

11.

409

mysql> describe users;


+----------------+--------------+------+-----+---------+----------------+
| Field
| Type
| Null | Key | Default | Extra
|
+----------------+--------------+------+-----+---------+----------------+
| user_id
| int(11)
| NO
| PRI | NULL
| auto_increment |
| username
| varchar(32) | NO
|
| NULL
|
|
| password
| varchar(16) | NO
|
| NULL
|
|
| first_name
| varchar(20) | NO
|
|
|
|
| last_name
| varchar(30) | NO
|
|
|
|
| email
| varchar(50) | NO
|
|
|
|
| facebook_url
| varchar(100) | YES |
| NULL
|
|
| twitter_handle | varchar(20) | YES |
| NULL
|
|
| bio
| text
| YES |
| NULL
|
|
| user_pic_path | text
| YES |
| NULL
|
|
+----------------+--------------+------+-----+---------+----------------+
10 rows in set (0.03 sec)



, , . (username) (password)
(NOT NULL)
,
.
SQL. , ,
, :
mysql> UPDATE users
->
SET username = "jroday",
->
password = "psych_rules"
-> WHERE user_id = 45;

, :
mysql> SELECT user_id, username, password, first_name, last_name
->
FROM users
-> WHERE user_id = 45;
+---------+----------+-------------+------------+-----------+
| user_id | username | password
| first_name | last_name |
+---------+----------+-------------+------------+-----------+
|
45 | jroday
| psych_rules | James
| Roday
|
+---------+----------+-------------+------------+-----------+
1 row in set (0.00 sec)

users,
.

410

4.


?
, , . -
. .

yy , ,
50 .

yy , tommy.n@dbc.org, ( ), , tn1954a.

yy .

users username? ?
-, , . , ,
, Gmail, iCloud
, , - .
-,
. - , - . , , - ,
, .

.
-, , .
?
. , ?

, . , 1Password
(www.agilebits.com/products/1Password), . ,
1Password ( $59,99 ) .

11.

411



. create_user.html?

HTML
-, . :
.
create_user.html, , ,
, :
<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
<link href="../css/jquery.validate.password.css" rel="stylesheet"
type="text/css" />
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript" src="../js/jquery.validate.js"></script>
<script type="text/javascript" src="../js/jquery.validate.password.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#signup_form").validate({
rules: {
password: {
minlength: 6
},
confirm_password: {
minlength: 6,
equalTo: "#password"
}
},
messages: {
password: {
minlength: " 6 "
},
confirm_password: {
minlength: " 6 ",
equalTo: " ."
}
}
});
});
</script>

412

4.

</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example"></div>
<div id="content">
<h1> </h1>
<p>, :</p>
<form id="signup_form" action="create_user.php"
method="POST" enctype="multipart/form-data">
<fieldset>
<label for="first_name">:</label>
<input type="text" name="first_name" size="20" class="required" />
<br />
<label for="last_name">:</label>
<input type="text" name="last_name" size="20" class="required" />
<br />
<label for="username"> :</label>
<input type="text" name="username" size="20" class="required" />
<br />
<label for="password">:</label>
<input type="password" id="password" name="password"
size="20" class="required password" />
<div class="password-meter">
<div class="password-meter-message"> </div>
<div class="password-meter-bg">
<div class="password-meter-bar"></div>
</div>
</div>
<br />
<label for="confirm_password"> :</label>
<input type="password" id="confirm_password" name="confirm_password"
size="20" class="required" /><br />
<label for="email"> :</label>
<input type="text" name="email" size="30" class="required email" />
<br />
<label for="facebook_url"> URL- Facebook:</label>
<input type="text" name="facebook_url" size="50" class="url" /><br />
<label for="twitter_handle"> Twitter:</label>
<input type="text" name="twitter_handle" size="20" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
<label for="user_pic"> :</label>
<input type="file" name="user_pic" size="30" /><br />
<label for="bio">:</label>
<textarea name="bio" cols="40" rows="10"></textarea>
</fieldset>
<br />
<fieldset class="center">

11.

413

<input type="submit" value=" " />


<input type="reset" value=" " />
</fieldset>
</form>
</div>
<div id="footer"></div>
</body>
</html>

jQuery,
www.jquery.com. jQuery

, JavaScript .
jQuery jQuery:
, .
www.jquery.bassistance.de.
create_user.html .
, (.11.8).

. 11.8.

414

4.

, create_user.html , . .
, . ,
: . , ,
type password.
jQuery jQuery,
, (.11.9).
, , , .
.
JavaScript!

. 11.9.


jQuery
- (.11.10). ,
. ,

11.

415

. ,
PHP-.

. 11.10.

. PHP, .


create_user.php.
, .
:
<?php
require_once '../scripts/app_config.php';
require_once '../scripts/database_connection.php';
$upload_dir = SITE_ROOT . "uploads/profile_pics/";

416

4.

$image_fieldname = "user_pic";
// PHP-
$php_errors = array(1 => ' . , php.ini',
2 => ' . , HTML',
3 => ' ',
4 => ' .');
$first_name = trim($_REQUEST['first_name']);
$last_name = trim($_REQUEST['last_name']);
$username = trim($_REQUEST['username']);
$password = trim($_REQUEST['password']);
$email = trim($_REQUEST['email']);
$bio = trim($_REQUEST['bio']);
$facebook_url = str_replace("facebook.org", "facebook.com", trim($_
REQUEST['facebook_url']));
$position = strpos($facebook_url, "facebook.com");
if ($position === false) {
$facebook_url = "http://www.facebook.com/" . $facebook_url;
}
$twitter_handle = trim($_REQUEST['twitter_handle']);
$twitter_url = "http://www.twitter.com/";
$position = strpos($twitter_handle, "@");
if ($position === false) {
$twitter_url = $twitter_url . $twitter_handle;
} else {
$twitter_url = $twitter_url . substr($twitter_handle, $position + 1);
}
//
($_FILES[$image_fieldname]['error'] == 0)
or handle_error(" .",
$php_errors[$_FILES[$image_fieldname]['error']]);
// ?
@is_uploaded_file($_FILES[$image_fieldname]['tmp_name'])
or handle_error(" . !",
" : " .
['tmp_name']}'");
// ?
@getimagesize($_FILES[$image_fieldname]['tmp_name'])
or handle_error(" , " .
" .",
"{$_FILES[$image_fieldname]['tmp_name']} " .
" .");
//
$now = time();
while (file_exists($upload_filename = $upload_dir . $now .
'-' .
$_FILES[$image_fieldname]['name'])) {

11.

417

$now++;
}
// ,
@move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],
$upload_filename)
or handle_error(" " .
" .",
", " .
" {$upload_filename}");
$insert_sql = sprintf("INSERT INTO users " .
"(first_name, last_name, username, " .
"password, email, " .
"bio, facebook_url, twitter_handle, " .
"user_pic_path) " .
"VALUES ('%s', '%s', '%s', '%s', '%s',
'%s', '%s', '%s', '%s');",
mysql_real_escape_string($first_name),
mysql_real_escape_string($last_name),
mysql_real_escape_string($username),
mysql_real_escape_string($password),
mysql_real_escape_string($email),
mysql_real_escape_string($bio),
mysql_real_escape_string($facebook_url),
mysql_real_escape_string($twitter_handle),
mysql_real_escape_string($upload_filename));
//
mysql_query($insert_sql);
// ,
//
header("Location: show_user.php?user_id=" . mysql_insert_id());
?>

, , create_user.php ( create_user.html). ,
, 9 10,
. , ,
-, .

, -
, , .11.11.
, . , ,
require_once
authorize.php. ,
.

418

4.

. 11.11.

create_user.php
?
, . , create_user.php
, . , , .
SELECT . - ,
, handle_error. . ,
, , ,
.
create_user.html create_user.php. , - ,
, , , .
, , , Ajax, .
, ?
. PHP . , , , ,
, , 12,
.
.

419

11.

authorize.php
users
:
authorize.php.
, :
define(VALID_USERNAME, "admin");
define(VALID_PASSWORD, "super_secret");

authorize.php users,
.
, authorize.php users - .
authorize.php , . require_once,
database_connection.php, users:
<?php
require_once 'database_connection.php';
// define(VALID_USERNAME, "admin");
// define(VALID_PASSWORD, "super_secret");

if (!isset($_SERVER['PHP_AUTH_USER']) ||
!isset($_SERVER['PHP_AUTH_PW']) ||
($_SERVER['PHP_AUTH_USER'] != VALID_USERNAME) ||
($_SERVER['PHP_AUTH_PW'] != VALID_PASSWORD)) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="The Social Site"');
exit(" ." .
" . .");
}
?>

if. -. $_SERVER PHP_AUTH_USER PHP_AUTH_PW,


, .
VALID_USERNAME VALID_PASSWORD,
, . if . :
if (!isset($_SERVER['PHP_AUTH_USER']) ||
!isset($_SERVER['PHP_AUTH_PW'])) {
header('HTTP/1.1 401 Unauthorized');

420

4.

header('WWW-Authenticate: Basic realm="The Social Site"');


exit(" ." .
" . .");
}

, if (), else ( ),
else . if ,
exit, .
, PHP_AUTH_USER PHP_AUTH_PW
$_SERVER.

, .
, , - .
.
sprintf mysql_real_escape_string, :
<?php
require_once 'database_connection.php';
if (!isset($_SERVER['PHP_AUTH_USER']) ||
!isset($_SERVER['PHP_AUTH_PW'])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="The Social Site"');
exit(" ." .
" . .");
}
//
$query = sprintf("SELECT user_id, username FROM users " .
" WHERE username = '%s' AND " .
"
password = '%s';",
mysql_real_escape_string(trim($_SERVER['PHP_AUTH_USER'])),
mysql_real_escape_string(trim($_SERVER['PHP_AUTH_PW'])));
$results = mysql_query($query);
?>

. , .

. ,
, , . (
- . .)

11.

421

, , - .
, , ,
. :
if (mysql_num_rows($results) == 1) {
// ! .
} else {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="The Social Site"');
exit(" ." .
" . .");
}

, , , ,
, , , , exit,
authorize.php.

- . , , authorize.php,
:
if (mysql_num_rows($results) == 1) {
$result = mysql_fetch_array($results);
$current_user_id = $result['user_id'];
$current_username = $result['username'];
} else {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="The Social Site"');
exit(" ." .
" . .");
}

, , , ,
:
<?php
require_once 'database_connection.php';
if (!isset($_SERVER['PHP_AUTH_USER']) ||
!isset($_SERVER['PHP_AUTH_PW'])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="The Social Site"');
exit(" ." .

422

4.

" . .");
}
//
$query = sprintf("SELECT user_id, username FROM users " .
" WHERE username = '%s' AND " .
"
password = '%s';",
mysql_real_escape_string(trim($_SERVER['PHP_AUTH_USER'])),
mysql_real_escape_string(trim($_SERVER['PHP_AUTH_PW'])));
$results = mysql_query($query);
if (mysql_num_rows($results) == 1) {
$result = mysql_fetch_array($results);
$current_user_id = $result['user_id'];
$current_username = $result['username'];
} else {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="The Social Site"');
exit(" ." .
" . .");
}
?>

. (
, ), . , show_users.php,
, authorize.php. , , , .

,

, , , .

.
show_users.php
, , , admin.

11.

423

, SQL :
mysql> SELECT user_id, username, password, first_name, last_name
->
FROM users
-> WHERE user_id = 45;
+---------+----------+-------------+------------+-----------+
| user_id | username | password
| first_name | last_name |
+---------+----------+-------------+------------+-----------+
|
45 | jroday
| psych_rules | James
| Roday
|
+---------+----------+-------------+------------+-----------+
1 row in set (0.00 sec)

- ? ( , ,
James Roday. , Psych ,
, .)

. ,
, , , .

. , ,
,
,
.
, - . , : PHP ,
.

crypt
- .
PHP- crypt. (
, ), , :
$encrypted_password = crypt($password);

, create_user.php
:
$insert_sql = sprintf("INSERT INTO users " .
"(first_name, last_name, username, " .
"password, email, " .
"bio, facebook_url, twitter_handle, " .
"user_pic_path) " .
"VALUES ('%s', '%s', '%s', '%s', '%s',
'%s', '%s', '%s', '%s');",

424

4.

mysql_real_escape_string($first_name),
mysql_real_escape_string($last_name),
mysql_real_escape_string($username),
mysql_real_escape_string(crypt($password)),
mysql_real_escape_string($email),
mysql_real_escape_string($bio),
mysql_real_escape_string($facebook_url),
mysql_real_escape_string($twitter_handle),
mysql_real_escape_string($upload_filename));

, create_user.php , users:
mysql> SELECT user_id, username, password, last_name
->
FROM users
-> WHERE user_id = 51;
+---------+----------+------------------+-----------+
| user_id | username | password
| last_name |
+---------+----------+------------------+-----------+
|
51 | traugott | $1$qzifqLu4$0C88 | Traugott |
+---------+----------+------------------+-----------+
1 row in set (0.00 sec)

. -, , ,
, crypt .
ALTER TABLE users
CHANGE password
password VARCHAR(50) NOT NULL;

password . ,
. ,
( NOT NULL). ,
, password.

, ?


crypt
crypt .
, , .
, .
, , , .
. - ,

11.

425

. ,
. ,
, , - .
,
, ?
:
.
, , .
, authorize.php (, )
- :
//
$query = sprintf("SELECT user_id, username FROM users " .
" WHERE username = '%s' AND " .
"
password = '%s';",
mysql_real_escape_string(trim($_SERVER['PHP_AUTH_USER'])),
mysql_real_escape_string(
crypt(trim($_SERVER['PHP_AUTH_PW']))));

. , , .

.
, ,
.
, ,
, .11.11. ,
crypt.
?


crypt?
. , ,
,
, crypt. .
, , crypt
- . crypt ,
. , crypt

.

426

4.

test_salt.php:
<?php
$input = "secret_string";
$first_output = crypt($input);
$second_output = crypt($input);
echo " : {$first_output}\n\n";
echo " : {$second_output}\n\n";
?>

:
yellowta@yellowtagmedia.com [~/www/phpMM/ch11]# php test_salt.php
X-Powered-By: PHP/5.2.17
Content-type: text/html
: $1$ciU1qEcc$XFT9G7FD/4K/L1Kl.bd.q/
: $1$7cLtF/bc$Js6rEk5RHg4PujAkVOOSG1

. , .
:
<?php
$input = "secret_string";
$salt = "salt";
$first_output = crypt($input, $salt);
$second_output = crypt($input, $salt);
echo " : {$first_output}\n\n";
echo " : {$second_output}\n\n";
?>

:
yellowta@yellowtagmedia.com [~/www/phpMM/ch11]# php test_salt.php
X-Powered-By: PHP/5.2.17
Content-type: text/html
: sazmIw2D3KJ/M
: sazmIw2D3KJ/M

, crypt
.
, : ! -

11.

427

, ,
-.
, , , ,
,
.
create_user.php (, !),
:
$insert_sql = sprintf("INSERT INTO users " .
"(first_name, last_name, username, " .
"password, email, " .
"bio, facebook_url, twitter_handle, " .
"user_pic_path) " .
"VALUES ('%s', '%s', '%s', '%s', '%s',
'%s', '%s', '%s', '%s');",
mysql_real_escape_string($first_name),
mysql_real_escape_string($last_name),
mysql_real_escape_string($username),
mysql_real_escape_string(crypt($password, $username)),
mysql_real_escape_string($email),
mysql_real_escape_string($bio),
mysql_real_escape_string($facebook_url),
mysql_real_escape_string($twitter_handle),
mysql_real_escape_string($upload_filename));

authorize.php.
,
$_SERVER:
//
$query = sprintf("SELECT user_id, username FROM users " .
" WHERE username = '%s' AND " .
"
password = '%s';",
mysql_real_escape_string(trim($_SERVER['PHP_AUTH_USER'])),
mysql_real_escape_string(
crypt(trim($_SERVER['PHP_AUTH_PW']),
$_SERVER['PHP_AUTH_USER'])));

, , (,
!). , .
show_users.php
, . , ,
. . , ...
.

12

Cookie-,

PHP

,
,
MySQL
, , .
, , -,

Twitter
URL

-
Facebook
Google .
, PHP

.
,
, .
, .
.

, , .
,

.
.
: ,

, ,
, show_users.php delete_user.php.

12. Cookie-,

429

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

, HTTP-. ,

HTTP
- , ,
.12.1.
, ,
, .

. ,
. ,
.

. 12.1.

430

4.

:
, ,
. , ,
,
CSS

HTML
5
SVG
, . ,
,
.
- .
, .


, , -,
, .
-
. .
. index.html,
:
<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="content">
<div id="home_banner"></div>
<div id="signup">
<a href="create_user.html"><img src="../images/sign_me_up.png" /></a>
<a href="signin.html"><img src="../images/sign_me_in.png" /></a>
</div>
</div>
<div id="footer"></div>
</body>
</html>

, .

12.2. , , , 2.0.
: -

12. Cookie-,

431

, . , ?
, , ,
PHP
, HTTP

-.

. 12.2.

:
create_user.html
. signin.html
, . :
?

432

4.



, , , . ,
, .
, :
,
authorize.php. ,
.
,
.
, authorize.php, ,
$_SERVER, . :
, ,
, .

, , , , .
.

.
1. (HTML)
.
2. (
PHP
) . , ,
(show_user.php), ,
. ,
(HTML).
: HTML-
?
?
HTML
, ,
. PHP .

12. Cookie-,

433


PHP.
.
1. (
PHP
) . (PHP).
2. (
PHP
) . , ,
(show_user.php), ,
. ,
(PHP).
3. (PHP)
.
? . ,
,
? ( , ,
, PHP

.)
, , .
, ,
PHP, :
<html>
<head>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="content">
<div id="home_banner"></div>
<div id="signup">
<a href="create_user.html"><img src="../images/sign_me_up.png" /></a>
<a href="signin.php"><img src="../images/sign_me_in.png" /></a>
</div>
</div>
<div id="footer"></div>
</body>
</html>

434

4.

PHP
,
HTML, , ,
PHP. , -
, , HTML-.
?
...
. , . ,
, . , if, .
if ,
, , .
, , ,
, , . .

.
PHP,
, . , , , , PHP, ,
PHP, . , ,
...
, PHP,
.
, - (Model-View-Controller, MVC), .
HTML , ,
( - ) , . , ,
MVC-, PHP.
.
, , Ruby
Java ( , ).
, PHP
MVC,
. .

12. Cookie-,

435

HTTP-
ookie-
( signin.php),
. ? , .
,
, .
signin.php. . HTTP- ,
,
. show_users.php , , delete_user.php.
.
ookie-.

,
(cookie . , , , , ).
, (magic cookies).
Unix , - .
, ookie-
, ,
.

ookie-?
cookie

- . , . cookie- ,
, ,
. , cookie- ,
.
, cookie- username
my_username , , cookie- user_id 52.
cookie- username , , , .
cookie- username.
, cookie-
, . ,
cookie- ,

436

4.

, (,
)
cookie-.

cookie- , ,
cookie-.
, :
.
13. ,
cookie-. , ,
. , cookie ,
.

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

PHP
cookie

- , $_SERVER $_REQUEST, .
cookie- setcookie
cookie- :
setcookie("username", "my_username");

cookie-
$_COOKIE:
echo " " . $_COOKIE['username'] . ".";

. . , ,
, cookie-
. setcookie $_COOKIE, .

cookie- , ,
. setcookie ,
.


cookie-
, cookie-.
. .
signin.php :

12. Cookie-,

<?php
require_once '../scripts/database_connection.php';
require_once '../scripts/view.php';
// , cookie- user_id
if (!isset($_COOKIE['user_id'])) {
// username
if (isset($_REQUEST['username'])) {
//
$username = mysql_real_escape_string(trim($_REQUEST['username']));
$password = mysql_real_escape_string(trim($_REQUEST['password']));
//
// ,
}
// if,
// .
// . ,
// ,
// .
page_start("");
?>
<html>
<div id="content">
<h1> </h1>
<form id="signin_form" action="signin.php" method="POST">
<fieldset>
<label for="username"> :</label>
<input type="text" name="username" id="username" size="20" />
<br />
<label for="password">:</label>
<input type="password" name="password" id="password" size="20" />
</fieldset>
<br />
<fieldset class="center">
<input type="submit" value="" />
</fieldset>
</form>
</div>
<div id="footer"></div>
</body>
</html>
<?php
} else {

437

438

4.

// ,
// , , show_user.php
}
?>

, database_connection.php ,
app_config.php ? app_config.php, ,
- , . , -
database_connection.php app_config.php. ,
database_connection.php, app_config.php.

, ,
. .

?

. , ( require_once), ,
cookie- user_id. , ,
.
<?php
require_once '../scripts/database_connection.php';
require_once '../scripts/view.php';
// ,
// cookie- user_id
if (!isset($_COOKIE['user_id'])) {

, , cookie-
, : ,
, isset, cookie-.
.

?
cookie- user_id , , .
, , .
, . HTML- ( )
.
-
.

12. Cookie-,

439

HTML- . , ,
, , $_REQUEST
- username, :
//
if (isset($_REQUEST['username'])) {
//
$username = mysql_real_escape_string(trim($_REQUEST['username']));
$password = mysql_real_escape_string(trim($_REQUEST['password']));
//
// ,
}


.
.
$_REQUEST. GET-,
URL, POST-,
, . ,
, POST-.
, $_REQUEST $_POST, ,
POST-.

, , , $_POST GET-:
$_GET.

$_POST
.
POST
- URL .

. POST- , GET-,
. , , POST, . .

:
//
if (isset($_POST['username'])) {
//
$username = mysql_real_escape_string(trim($_REQUEST['username']));

440

4.

$password = mysql_real_escape_string(trim($_REQUEST['password']));
//
// ,
}

, : $_REQUEST $_POST?
, ,
. , ,
$_REQUEST, $_GET $_POST . $_REQUEST , $_GET, $_POST. ,
POST-, ,
$_REQUEST, $_POST.
$_REQUEST $_GET
$_POST. $_COOKIE (
). , signin.php
:
// , cookie- user_id
if (!isset($_REQUEST['user_id'])) {

, $_REQUEST $_GET,
$_REQUEST $_COOKIE. , : , ,
, , .
, , $_REQUEST,
$_GET, $_POST $_COOKIE.
signin.php, , POST-.
, , , $_POST.
GET-, $_GET.
cookie-,
$_COOKIE. ... ,
.


, .
, HTML-.

12. Cookie-,

441

, . , ,
.

// if,
// .
// . ,
// ,
// .
page_start("");
?>
<html>
<div id="content">
<h1> </h1>
<form id="signin_form" action="signin.php" method="POST">
<fieldset>
<label for="username"> :</label>
<input type="text" name="username" id="username" size="20" />
<br />
<label for="password">:</label>
<input type="password" name="password" id="password" size="20" />
</fieldset>
<br />
<fieldset class="center">
<input type="submit" value="" />
</fieldset>
</form>
</div>
<div id="footer"></div>
</body>
</html>

,
. , HTML,
if:
// ,
// cookie- user_id
if (!isset($_COOKIE['user_id'])) {

,
HTML
, .
, $_POST $_REQUEST. :
<form id="signin_form" action="signin.php" method="POST">

442

4.

,
. . , signin.php? , ,
. (
admin.php delete_user.php
show_users.php.)
, PHP

. ,
$_SERVER, .
, ,
. signin.php
$_SERVER['PHP_SELF']:
<form id="signin_form"
action="<?php echo $_SERVER['PHP_SELF']; ?>"
method="POST">

. ,
, .


, , :
<?php
} else {
// ,
// , , show_user.php
}
?>

, .
. .


, signin.php
, . , ,
. , , . , ,
.

12. Cookie-,

443

, .

check_the_user_credentials().
:
//
// ,

.
, .
, . , , HTML- PHP, ,
POST-. .12.3 ,
, . ,

PHP
-, , . HTML-,
, cookie- user_id
POST
- .

. 12.3. ,


, .
, .
.

444

4.




authorize.php . :
//
$query = sprintf("SELECT user_id, username FROM users " .
" WHERE username = '%s' AND " .
"
password = '%s';",
mysql_real_escape_string(trim($_SERVER['PHP_AUTH_USER'])),
mysql_real_escape_string(
crypt(trim($_SERVER['PHP_AUTH_PW']),
$_SERVER['PHP_AUTH_USER'])));
$results = mysql_query($query);
if (mysql_num_rows($results) == 1) {
$result = mysql_fetch_array($results);
$current_user_id = $result['user_id'];
$current_username = $result['username'];
} else {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="The Social Site"');
exit(" ." .
" . .");
}

, HTTP-.
signin.php, ,
cookie- , -
:
<?php
require_once '../scripts/database_connection.php';
require_once '../scripts/view.php';
// ,
// cookie- user_id
if (!isset($_COOKIE['user_id'])) {
//
if (isset($_POST['username'])) {
//
$username = mysql_real_escape_string(trim($_REQUEST['username']));
$password = mysql_real_escape_string(trim($_REQUEST['password']));
//
$query = sprintf("SELECT user_id, username FROM users " .

12. Cookie-,

445

" WHERE username = '%s' AND " .


"
password = '%s';",
$username, crypt($password, $username));
$results = mysql_query($query);
if (mysql_num_rows($results) == 1) {
$result = mysql_fetch_array($results);
$user_id = $result['user_id'];
setcookie('user_id', $user_id);
setcookie('username', $result['username']);
header("Location: show_user.php");
} else {
// ,
}
}
// if,
// .
// . ,
// ,
//
page_start("");
?>

, signin.php,
( .12.2, ,

HTML
). - , .
cookie

-, show_user.php (.12.4).
?
, :
if (mysql_num_rows($results) == 1) {
$result = mysql_fetch_array($results);
$user_id = $result['user_id'];
setcookie('user_id', $user_id);
setcookie('username', $result['username']);
header("Location: show_user.php");
} else {
// ,
}

, create_
user.php.
show_user.php. :
header("Location: show_user.php?user_id=" . mysql_insert_id());

446

4.

. 12.4. show_user.php
,

,
GET
- URL

- : user_id . signin.php user_id. .

12.4 , .
show_user.php :
// ID
$user_id = $_REQUEST['user_id'];

, show_user.php
. signin.php
if:
// ,
// cookie- user_id
if (!isset($_COOKIE['user_id'])) {

else, if,
:
} else {
// ,

12. Cookie-,

447

// , , show_user.php
header("Location: show_user.php");

, , show_user.php. user_id,
show_user.php , , (..12.4).
, signin.php?
$_REQUEST ,
( :
, : $_REQUEST $_POST? ).
signin.php cookie

-, $_COOKIE. $_REQUEST ,
$_COOKIE, , $_POST $_GET. :
$user_id = $_REQUEST['user_id'];

, :
$user_id = $_COOKIE['user_id'];

, cookie-.

: : $_COOKIE $_REQUEST?
. , $_COOKIE,
create_user.php. , - $_REQUEST,
show_user.php .
cookie-, . ,
cookie-, show_user.php, $_COOKIE,
.


cookie-
.
signin.php, Enter
(.12.5).
, , . ! , ,
. signin.php,
. ?
- , . ,
cookie-:
// ,
// cookie- user_id
if (!isset($_COOKIE['user_id'])) {

448

4.

. 12.5.

cookie- , ,
:
<?php
} else {
// ,
// , , show_user.php
}
?>

! . (),
, signin.php
. , ,
: show_user.php:
} else {
// ,
// , , show_user.php
header("Location: show_user.php");
}

. show_user.php cookie-
user_id . ?
. - .
show_user.php,
. , .
. ,
HTTP-, cookie-
cookie- ,
.

setcookie , 0,
, cookie- ,
.

12. Cookie-,

449

, .
, , .
cookie-
.
cookie- (
), setcookie
. ,
Unix Linux, 0:00 1 1970.
, , , . , time() + 10 10 ,
.
setcookie
cookie-:
// (60 seconds * 60 minutes = 3600)
setcookie('user_id', $user_id, time() + 3600);
// cookie-,
//
setcookie('user_id', $user_id, time() - 3600);
// :
setcookie('user_id', $user_id, 0);

mktime,
, , , , , , . :
setcookie('user_id', $user_id, mktime(0, 0, 0, 2, 1, 2021);

cookie

- 1 2021, . , , , . , .

. ,
.

, Facebook Twitter,
.
, 10.

, , cookie-,
signin.php .

450

4.



, .
else, , :
if (mysql_num_rows($results) == 1) {
// cookie- show_user.php
} else {
// ,
}

handle_error.
, , . ,
. .
, ,
. , handle_error.
. ,
handle_error.
: page_start
view.php. signin.php, , :
page_start("");

view.php,
:
function page_start($title, $javascript = NULL,
$success_message = NULL, $error_message = NULL) {


$success_message $error_message. .
$error_message, , page_start,

HTML-.
:
<?php
require_once '../scripts/database_connection.php';
require_once '../scripts/view.php';
$error_message = "";
// ,

12. Cookie-,

451

// cookie- user_id
if (!isset($_COOKIE['user_id'])) {
//
if (isset($_POST['username'])) {
//
//
if (mysql_num_rows($results) == 1) {
$result = mysql_fetch_array($results);
$user_id = $result['user_id'];
setcookie('user_id', $user_id);
setcookie('username', $result['username']);
header("Location: show_user.php");
} else {
// ,
$error_message = " -.";
}
}
// if,
// .
// ,
// .
page_start("", NULL, NULL, $error_message);
?>
<!-- HTML- -->
<?php
} else {
// ,
// , , show_user.php
header("Location: show_user.php");
}
?>

, cookie-
, .
, ID ,
cookie- .
, ! cookie-
, .
, cookie-.

signin.php ( index.html)
. , .12.6,
, - .

452

4.

. 12.6.

. , -, view.php,
. .
, page_start
$error_message,
, "", .
view.php display_message:
function display_messages($success_msg = NULL, $error_msg = NULL) {
echo "<div id='messages'>\n";
if (!is_null($success_msg)) {
display_message($success_msg, SUCCESS_MESSAGE);
}
if (!is_null($error_msg)) {
display_message($error_msg, ERROR_MESSAGE);
}
echo "</div>\n\n";
}

12. Cookie-,

453

$error_message . .
, .
.
, ,
$error_message , null, .

:
function display_messages($success_msg = NULL, $error_msg = NULL) {
echo "<div id='messages'>\n";
if (!is_null($success_msg) && (strlen($error_msg) > 0)) {
display_message($success_msg, SUCCESS_MESSAGE);
}
if (!is_null($error_msg) && (strlen($error_msg) > 0)) {
display_message($error_msg, ERROR_MESSAGE);
}
echo "</div>\n\n";
}

(.12.7).
, , . ,
, .12.8.

. 12.7.

454

4.

. 12.8. ,



. ,
: .
, .
, , ,
, , .
, signin.php:
if (isset($_POST['username'])) {
//
$username = mysql_real_escape_string(trim($_REQUEST['username']));
$password = mysql_real_escape_string(trim($_REQUEST['password']));
// . ...
}

12. Cookie-,

455

, . , $username.

HTML
. value $username.
, :
<label for="username"> :</label>
<input type="text" name="username" id="username" size="20"
value="<?php if (isset($username)) echo $username; ?>" />

, , . , ,

(.12.9).

. 12.9.

-
.

,
. PHP

456

4.

. PHP

- ,
.
, , . cookie- user_id:
if (isset($_COOKIE['user_id'])) {
//
} else {
//
}


view.php, , .
,
, .
display_title.
, if:
cookie- user_id, show_user.php signout.php (
). ,
. , , ,
:
function display_title($title, $success_message = NULL, $error_message = NULL)
{
echo <<<EOD
<body>
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example">$title</div>
<div id="menu">
<ul>
<li><a href="index.html"> </a></li>
EOD;
if (isset($_COOKIE['user_id'])) {
echo "<li><a href='show_user.php'> </a>";
echo "<li><a href='signout.php'> </a></li>";
} else {
echo "<li><a href='signin.php'></a></li>";
}
echo <<<EOD
</ul>
</div>
EOD;
display_messages($success_message, $error_message);
}

12. Cookie-,

457

. -, view.php. ,
HTML
if ,
. -, display_title,
, display_title, . .
, $_REQUEST
, $_COOKIE:
if (isset($_COOKIE['user_id'])) {
echo "<li><a href='show_user.php'> </a>";
echo "<li><a href='signout.php'> </a></li>";
} else {
echo "<li><a href='signin.php'></a></li>";
}

ID show_user.php,
cookie-. , show_user.php
$_REQUEST['user_id'],
, ID
.

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

, ,
, - . -, ,
, ,
. - . , .
, , , .
, cookie-. ,
. ,
.

458

4.

, ,
HTML: show_user.php, show_users.php signin.php.
page_start,
HTML
. ,
display_title, page_start
view.php. , , show_user.php:
<?php
require '../scripts/database_connection.php';
require '../scripts/view.php';
// PHP ID
// cookie-,
//
page_start("");
?>
<div id="content">
<div class="user_profile">
<h1><?php echo "{$first_name} {$last_name}"; ?></h1>
<p><img src="<?php echo $user_image; ?>" class="user_pic" />
<?php echo $bio; ?></p>
<p class="contact_info">
<?php echo $first_name; ?>:
</p>
<ul>
<li>...
<a href="<?php echo $email; ?>"><?php echo $email; ?></a></li>
<li>...
<a href="<?php echo $facebook_url; ?>">
Facebook</a></li>
<li>... <a href="<?php echo $twitter_url; ?>">
Twitter</a></li>
</ul>
</div>
</div>
<div id="footer"></div>
</body>
</html>

show_user.php.

- show_user.php
. !

- .12.10.
start_page, display_title, view.php cookie-,

12. Cookie-,

459

signin.php, . , , .
, ,
if display_title, cookie-,
.

. 12.10.

HTML
, show_user.php, show_users.php
signin.php, . index.html,
, create_user.html. , ,
start_page view.php,
HTML, PHP. , index.html
. :
,
.
create_user.html . , -
, ,

460

4.

. , , , ,
.
, .

HTML PHP
create_user.html create_user.php . ,
create_user.php .
create_user.html signup.php. , index.html,
(sign up) .
[~/www/phpMM/ch12]# cp create_user.html create_user.html.orig
[~/www/phpMM/ch12]# mv create_user.html signup.php

,
.
, ,
, ,
.


HTML
PHP page_start.
JavaScript-, ,
heredoc.
<?php
require_once "../scripts/view.php";
$inline_javascript = <<<EOD
$(document).ready(function() {
$("#signup_form").validate({
rules: {
password: {
minlength: 6
},
confirm_password: {
minlength: 6,
equalTo: "#password"
}
},
messages: {
password: {
minlength: " 6 "
},
confirm_password: {

12. Cookie-,

461

minlength: " 6 ",


equalTo: " ."
}
}
});
});
EOD;
page_start(" ", $inline_javascript);
?>
<div id="content">
<h1> </h1>
<p>, :</p>
<form id="signup_form" action="create_user.php"
method="POST" enctype="multipart/form-data">
<!-- -->
</form>
</div>
<div id="footer"></div>
</body>
</html>

view.php,
jQuery, CSS,
signin.php.
:
function display_head($page_title = "", $embedded_javascript = NULL) {
echo <<<EOD
<html>
<head>
<title>{$page_title}</title>
<link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
<link href="../css/jquery.validate.password.css" rel="stylesheet"
type="text/css" />
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript" src="../js/jquery.validate.js"></script>
<script type="text/javascript"
src="../js/jquery.validate.password.js"></script>
EOD;
if (!is_null($embedded_javascript)) {
echo "<script type='text/javascript'>" .
$embedded_javascript .
"</script>";
}
echo " </head>";
}

462

4.

index.html, signup.php,
create_user.html:
<div id="content">
<div id="home_banner"></div>
<div id="signup">
<a href="signup.php"><img src="../images/sign_me_up.png" /></a>
<a href="signin.php"><img src="../images/sign_me_in.png" /></a>
</div>
</div>

,
. .

12.11. . ,
, .

. 12.11.

:

, , , . , . -

12. Cookie-,

463

jQuery
JavaScript,
.

. . signin.php create_user.php.


,
. cookie- (,
, ), . .
cookie-, ,
:
setcookie('user_id', $user_id);
//
setcookie('username', $result['username']); //
//

.
cookie

- :
// cookie- user_id
setcookie('user_id', '', time()-(60*60*24*365));

cookie- user_id , .

. ,
, .
, .

.

cookie
-, user_id username, - :
<?php
setcookie('user_id', '', time()-(365*24*60*60));
setcookie('username', '', time()-(365*24*60*60));
header('Location: signin.php');
?>

464

4.

, ( cookie-)
. show_user.php, show_users.php .
.

.
, .

. . ,
ID , .
, , , , , .
.12.12.

. 12.12. ,

, , ,
: , -
. ,

. , .

12. Cookie-,

465

cookie-
, . show_user.php

authorize.php.
, , ,
HTTP-.
.
authorize.php
signin.php.
. ,
signin.php.
.
authorize.php,
cookie-:
<?php
if ((!isset($_COOKIE['user_id'])) ||
(!strlen($_COOKIE['user_id']) > 0)) {
}
?>

cookie

- , ,
:
<?php
if ((!isset($_COOKIE['user_id'])) ||
(!strlen($_COOKIE['user_id']) > 0)) {
header('Location: signin.php?' .
'error_message=You must login to see this page.');
//
exit;
}
?>

exit . ,
show_user.php, delete_user.php, , ,
. -
.

, require_once
show_user.php, show_users.php delete_user.php.

. , ( , signout.php

466

4.

). show_user.php. , . , .12.13, .

. ... ? ,
URL , .

. 12.13.

? signin.php , , URL .
, .
signin.php :
require_once '../scripts/view.php';
$error_message = "";
// ,
// cookie- user_id
if (!isset($_COOKIE['user_id'])) {

.
$error_message:

12. Cookie-,

467

// if,
// .
// ,
// .
page_start("", NULL, NULL, $error_message);

- , - :
<?php
require_once '../scripts/database_connection.php';
require_once '../scripts/view.php';
$error_message = $_REQUEST['error_message'];
// ,
// cookie- user_id
if (!isset($_COOKIE['user_id'])) {

. .
show_user.php cookie-, -
, .12.14.

. 12.14. ,

468

4.

, ? .
. -

, , .
(!)
,

. (!)
. (!)
: ,

, ,
, show_users.php delete_user.php. (
.)
- ,

, .
(- .)
, . ,
: , cookie

-, , , .

13

. ,
:
: ,

, , , show_users.php delete_user.php;
- ,

, .
, , authorize.php. : authorize.php. (, ,
) ,
, .
. ,
, .
: ,
,
show_users.php (
show_user.php).
, , cookie-. , ,
,
,
cookie-. , .


. ,
, . , , , ,
. . .

470

4.

.
1. .
2. , .
3. PHP .
4. .
.

groups
, PHP MySQL,
. , , MySQL , , ,
NOT NULL,
:
mysql> CREATE TABLE groups (
->
id
INT
NOT NULL AUTO_INCREMENT PRIMARY KEY,
->
name
VARCHAR(30) NOT NULL,
->
description VARCHAR(200)
-> );
Query OK, 0 rows affected (0.03 sec)
mysql> DESCRIBE groups;
+-------------+--------------+------+-----+---------+----------------+
| Field
| Type
| Null | Key | Default | Extra
|
+-------------+--------------+------+-----+---------+----------------+
| id
| int(11)
| NO
| PRI | NULL
| auto_increment |
| name
| varchar(30) | NO
|
| NULL
|
|
| description | varchar(200) | YES |
| NULL
|
|
+-------------+--------------+------+-----+---------+----------------+
3 rows in set (0.03 sec)

, . description
, NOT NULL. , .
,
groups:
mysql> INSERT INTO groups
->
(name, description)
-> VALUES ("Administrators",
->
"- .");
Query OK, 1 row affected (0.04 sec)
mysql> INSERT INTO groups

13.

471

->
(name, description)
-> VALUES ("Luthiers",
->
" . .");
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO groups
->
(name, description)
-> VALUES ("Musicians",
->
", , .
.");
Query OK, 1 row affected (0.00 sec)

, . ,
Administrators. - -,
, Administrators ,
.

, , :
mysql> SELECT id, name FROM groups;
+----+----------------+
| id | name
|
+----+----------------+
| 1 | Administrators |
| 2 | Luthiers
|
| 3 | Musicians
|
+----+----------------+
3 rows in set (0.01 sec)


? SQL, ,
. ,
.

, ,
.
, users,
images. , users images
.
. ,
, , . ,
Luthier, Musician Administrator. ,
.

472

4.

, . .
. , , , . , 0, 1, 1000 .
.
. .
Administrators , , 4, 5 12. , ,
, .
(,
, )
. ,
. , . ,
.

,
. , . - () ().


:
, , , - .
,
.
(1--1 1:1).
.
1--N. N ,
n, N. N
. , N ,
- .
, , 1:N.
1:N .
, .
1:N, , .

13.

473

, , N:N, ,
. N:N (
, ) . ,
N:N
.



, (
ID
).
ID
, . user_id,
users.
:
SELECT *
FROM images
WHERE user_id = $user_id;

:
SELECT u.username, u.first_name, u.last_name, i.filename, i.image_data
FROM users u, images i
WHERE u.id = i.user_id;

.
. , .
user_id, 51 ( 2931,
- , users).
users groups
. ?


users groups
(ID) ,
.
, ID

. : ID ID
.

474

4.

.
,
, users groups
. : users.
, . : groups.
.

. , users ,
. user_groups
, user_id group_id. ,
user_id : ID
Administrators ID Musicians. users groups.
groups
users. ID Administrators user_groups
, , .
:
mysql> CREATE TABLE user_groups (
->
user_id INT NOT NULL,
->
group_id INT NOT NULL
-> );
Query OK, 0 rows affected (0.03 sec)

:
. , ,
, 51, Luthiers,
, 2, user_groups
:
mysql> INSERT INTO user_groups
->
(user_id, group_id)
-> VALUES (51, 2);
Query OK, 1 row affected (0.02 sec)
mysql> select * from user_groups;
+---------+----------+
| user_id | group_id |
+---------+----------+
|
51 |
2 |
+---------+----------+
1 row in set (0.00 sec)
users groups .

13.

475


, ,
user_groups ,
ID
, :
mysql> SELECT COUNT(*)
->
FROM users u, groups g, user_groups ug
-> WHERE u.username = "traugott"
->
AND g.name = "Luthiers"
->
AND u.user_id = ug.user_id
->
AND g.id = ug.group_id;
+----------+
| COUNT(*) |
+----------+
|
1 |
+----------+
1 row in set (0.00 sec)

! ,
, .
COUNT(*), , .
: users, groups user_groups.
SELECT COUNT(*)
FROM users u, groups g, user_groups ug

(
, ),
. (
) users groups:
SELECT
FROM
WHERE
AND

COUNT(*)
users u, groups g, user_groups ug
u.username = "traugott"
g.name = "Luthiers"

( ID)
user_groups. ,
ID
user_groups:
SELECT
FROM
WHERE
AND
AND
AND

COUNT(*)
users u, groups g, user_groups ug
u.username = "traugott"
g.name = "Luthiers"
u.user_id = ug.user_id
g.id = ug.group_id;

476

4.

, users
user_groups,
groups. ? -
COUNT, 1,
users :
+----------+
| COUNT(*) |
+----------+
|
1 |
+----------+

COUNT, 0, :
mysql> SELECT COUNT(*)
->
FROM users u, groups g, user_groups ug
-> WHERE u.username = "traugott"
->
AND g.name = "Administrators"
->
AND u.user_id = ug.user_id
->
AND g.id = ug.group_id;
+----------+
| COUNT(*) |
+----------+
|
0 |
+----------+
1 row in set (0.05 sec)

! , COUNT,
. , ,
.

PHP.


.
, , ,
. ,
, , .
: .
,
authorize.php: ,
.
. , , , .

13.

477

,
. , authorize.php .

authorize.php
authorize.php . , authorize.php
, PHP-:
<?php
if ((!isset($_COOKIE['user_id'])) || (!strlen($_COOKIE['user_id']) > 0)) {
header('Location: signin.php?' .
'error_message= .');
//
exit;
}
?>

. .
, authorize.php,
, . ,
, ,
. ,
. ( , .)
authorize.php . , .

:
:
<?php
function authorize_user($groups = NULL) {
// cookie-,
if ((!isset($_COOKIE['user_id'])) ||
(!strlen($_COOKIE['user_id']) > 0)) {
header('Location: signin.php?' .
'error_message= .');
exit;
}
}
?>

478

4.

show_user.php .
- . show_user.php
:
<?php
require '../scripts/authorize.php';
require '../scripts/database_connection.php';
require '../scripts/view.php';
//
authorize_user();
// ID ,
$user_id = $_REQUEST['user_id'];
// SELECT
// . ...

.
, , ,
show_user.php . URL
. , .13.1.

. 13.1.

13.

479


.
authorize_user PHP.
show_users.php delete_user.php,
Administrators.
<?php
require_once
require_once
require_once
require_once

'../scripts/app_config.php';
'../scripts/authorize.php';
'../scripts/database_connection.php';
'../scripts/view.php';

//
// Administrators
authorize_user(array("Administrators"));
// PHP HTML-

, , show_users.php.
delete_user.php, .


authorize.php ,
. .
: , , ,
.
:
<?php
$message = "hello\n\n";
require_once "print.php";
?>

, test.php. ,
print.php, , :
<?php
echo $message;
?>

print.php, ,
print.php, ,

480

4.

require_once. , PHP

:
<?php
$message = "hello\n\n";
echo $message;
?>

test.php :
yellowta@yellowtagmedia.com [~/www/phpMM/ch13]# php test.php
X-Powered-By: PHP/5.2.17
Content-type: text/html
hello

,
.
, -
. , .
:
$allowed_groups = array("Musicians", "Luthiers");
require_once "../scripts/authorize.php";

. , $allowed_groups
require_once, authorize.
php, authorize.php .
authorize_user . ,
, , ,
, .
, , PHP
- . authorize.php
, .
, .
authorize_user ,
, NULL.
.
<?php
function authorize_user($groups = NULL) {
// cookie-,
if ((!isset($_COOKIE['user_id'])) ||
(!strlen($_COOKIE['user_id']) > 0)) {
header('Location: signin.php?' .
'error_message= .');
exit;
}
// ,

13.

481

if ((is_null($groups)) || (empty($groups))) {
return;
}

}
?>

empty PHP. ,
(empty), true, false. ,
empty true, .

return
PHP
, . , .


, ,
show_users.php delete_user.php. authorize.
php
SQL-.
$groups. for, : foreach.
foreach
:
$my_array = array("first", "second", "third");
foreach ($my_array as $item) {
echo $item;
}

, $groups :
foreach ($groups as $group) {
// SQL- $group
}

, . -
SQL, users
groups:
SELECT
FROM
WHERE
AND
AND
AND

COUNT(*)
users u, groups g, user_groups ug
u.username = "traugott"
g.name = "Luthiers"
u.user_id = ug.user_id
g.id = ug.group_id;

authorize.php. ,
users. ,

482

4.

user_id. user_id. :
SELECT
FROM
WHERE
AND
AND

COUNT(*)
user_groups ug, groups g
g.name = mysql_real_escape_string($group)
g.id = ug.group_id
ug.user_id = mysql_real_escape_string($_COOKIE['user_id']);

, mysql_real_escape_string,
. mysql_real_
escape_string ,
MySQL.

.
,
: 0 ( ) 1 ( ).
. , - . , ,
. , :
SELECT
FROM
WHERE
AND
AND

ug.user_id
user_groups ug, groups g
g.name = mysql_real_escape_string($group)
g.id = ug.group_id
ug.user_id = mysql_real_escape_string($_COOKIE['user_id']);

user_groups, , ug.group_id. , -
. ,
.
, foreach
:
foreach ($groups as $group) {
// SQL- $group
$query = "SELECT ug.user_id" .
" FROM user_groups ug, groups g" .
" WHERE g.name = '" . mysql_real_escape_string($group) . "'" .
"
AND g.id = ug.group_id" .
"
AND ug.user_id = " .
mysql_real_escape_string($COOKIE['user_id']) . "';";
mysql_query($query);
//
}

13.

483

users.
. , .
sprintf. , ,
. , ,
.

foreach:
//
$query_string =
"SELECT ug.user_id" .
" FROM user_groups ug, groups g" .
" WHERE g.name = '%s'" .
"
AND g.id = ug.group_id" .
"
AND ug.user_id = " . mysql_real_escape_string($_COOKIE['user_id']);
foreach ($groups as $group) {
// SQL- $group
//
}

foreach sprintf , :
//
$query_string =
"SELECT ug.user_id" .
" FROM user_groups ug, groups g" .
" WHERE g.name = '%s'" .
"
AND g.id = ug.group_id" .
"
AND ug.user_id = " . mysql_real_escape_string($_COOKIE['user_id']);
foreach ($groups as $group) {
// SQL- $group
$query = sprintf($query_string, mysql_real_escape_string($group));
$result = mysql_query($query);
//
}

, sprintf , $_COOKIE, ,
. sprintf ,
.

484

4.

,
?
, . , ,
.
, ,
.

:
SELECT COUNT(*)
FROM users u, groups g, user_groups ug
WHERE u.username =
mysql_real_escape_string($_COOKIE['username'])
AND g.name = mysql_real_escape_string($group)
AND u.user_id = ug.user_id
AND g.id = ug.group_id;

.
(users), , cookie-.
,
COUNT SELECT, user_groups. , -
.
.
,
sprintf .
,
.
. .
, .
.
,
.
,
.
,
, , ,
.

13.

485

, ,
, .
, :
, , ,
$group, ,
$group, $groups.
, , ,
, , authorize_user
.
$groups , ,
, PHP HTML,
.
: ,
. foreach ,
,
, , . .

.
?
handle_error.
. ,
, , .
,
- . , ,
- ,
.
authorize.php, , :
<?php
require_once 'database_connection.php';
require_once 'app_config.php';
function authorize_user($groups = NULL) {
// cookie-,
if ((!isset($_COOKIE['user_id'])) || (!strlen($_COOKIE['user_id']) > 0)) {
header('Location: signin.php?' .
'error_message= .');
exit;
}
// ,

486

4.

if ((is_null($groups)) || (empty($groups))) {
return;
}
//
$query_string =
"SELECT ug.user_id" .
" FROM user_groups ug, groups g" .
" WHERE g.name = '%s'" .
"
AND g.id = ug.group_id" .
"
AND ug.user_id = " . mysql_real_escape_string($_COOKIE['user_id']);

//
foreach ($groups as $group) {
$query = sprintf($query_string, mysql_real_escape_string($group));
$result = mysql_query($query);
if (mysql_num_rows($result) == 1) {
// , .
// , .
return;
}
}
// , .
// .
handle_error(" .");
exit;
}
?>

, -
. , users,
Administrators ( user_groups),
, .
show_users.php -
, ,
.13.2.
,
. ,
- , , , , . , .
, ,
, .

13.

487

. 13.2. ,

,

authorize_user , ,
, .
, ,
, - .
view.php:
function display_title($title, $success_message = NULL, $error_message = NULL)
{
echo <<<EOD
<body>
<div id="page_start">
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example">$title</div>
<div id="menu">
<ul>
<li><a href="index.html"> </a></li>

488

4.

EOD;
if (isset($_COOKIE['user_id'])) {
echo "<li><a href='show_user.php'></a></li>";
echo "<li><a href='signout.php'> </a></li>";
} else {
echo "<li><a href='signin.php'></a></li>";
}
echo <<<EOD
</ul>
</div>
EOD;
display_messages($success_message, $error_message);
echo "</div> <!-- , id="page_start" -->";
}

authorize_user ,
. ,
. - ,
true false.
- :
function display_title($title, $success_message = NULL, $error_message = NULL)
{
echo <<<EOD
<body>
<div id="page_start">
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example">$title</div>
<div id="menu">
<ul>
<li><a href="index.html"> </a></li>
EOD;
if (isset($_COOKIE['user_id'])) {
echo "<li><a href='show_user.php'></a></li>";
if (user_in_group($_COOKIE['user_id'], "Administrators")) {
echo "<li><a href='show_users.php'></a></li>";
}
echo "<li><a href='signout.php'> </a></li>";
} else {
echo "<li><a href='signin.php'></a></li>";
}
echo <<<EOD
</ul>
</div>
EOD;
display_messages($success_message, $error_message);
echo "</div> <!-- , id="page_start -->";
}

13.

489

, view.php require_once
authorize.php.

,
Administrators, .
authorize_user.php :
//
$query_string =
"SELECT ug.user_id" .
" FROM user_groups ug, groups g" .
" WHERE g.name = '%s'" .
"
AND g.id = ug.group_id" .
"
AND ug.user_id = " . mysql_real_escape_string($_COOKIE['user_id']);

//
foreach ($groups as $group) {
$query = sprintf($query_string, mysql_real_escape_string($group));
$result = mysql_query($query);
if (mysql_num_rows($result) == 1) {
// , .
// , .
return;
}
}

,
. , :
function user_in_group($user_id, $group) {
$query_string =
"SELECT ug.user_id" .
" FROM user_groups ug, groups g" .
" WHERE g.name = '%s'" .
"
AND g.id = ug.group_id" .
"
AND ug.user_id = %d";
$query = sprintf($query_string, mysql_real_escape_string($group),
mysql_real_escape_string($user_id));
$result = mysql_query($query);
if (mysql_num_rows($result) == 1) {
return true;
} else {
return false;
}
}

490

4.

. : ,
authorize.php authorize_user.
. , Administrators. , ,
show_user.php. (.13.3).

. 13.3. Administrators,

,
, .
, , PHP,
. .13.4.
. , .
: Administrators .
is_admin, , Administrators.

13.

491

. 13.4. Administrators


cookie-. ,
cookie-.
cookie- ,
. , ,
cookie
-, .
, . , cookie-. ,
cookie-. , Mozilla Firefox
- cookie-.
Cookie-, , .13.5.

492

4.

. 13.5. cookie- user_id username, ,


, cookie-

Safari cookie- .
, . Google Chrome
cookie
. Internet Explorer ,
.
.
, -.

13.

493

authorize_user
user_in_group?
, , user_in_group
, . , user_in_group $groups authorize_user .
user_in_group
foreach authorize_
user:
//
//
foreach ($groups as $group) {
if (user_in_group($_COOKIE['user_id'],
$group) {
// ,
return;
}
}

. , , ,
. , , authorize_user,
. , ( user_in_group). ,
, $groups.
, ( )
authorize_user.
. ,
? , authorize_user , ,
.
, , ... .
, cookie-.
- ,
,
.

494

4.

. ID
. , , cookie

-, , .

cookie
- ( ) . cookie-
- , .
, cookie-.
, ?


cookie-.

cookie
- , . .
, . -

. ,
, ,
.
,

, cookie-. ,
.
, .


. ,
cookie

-, . : session_
start:
// ()
session_start();
//

13.

495

: session_start
signin.php . ,
session_start:
<?php
require_once '../scripts/database_connection.php';
require_once '../scripts/view.php';
$error_message = $_REQUEST['error_message'];
session_start();
// PHP HTML...

session_start PHP-,
.

$_COOKIE $_SESSION
: $_COOKIE $_SESSION. :
<?php
require_once '../scripts/database_connection.php';
require_once '../scripts/view.php';
$error_message = $_REQUEST['error_message'];
session_start();
// ,
// user_id
if (!isset($_SESSION['user_id'])) {
// . ...

.
setcookie . $_SESSION, :
if (!isset($_SESSION['user_id'])) {
//
if (isset($_POST['username'])) {
//
$username = mysql_real_escape_string(trim($_REQUEST['username']));
$password = mysql_real_escape_string(trim($_REQUEST['password']));
//

496

4.

$query = sprintf("SELECT user_id, username FROM users " .


" WHERE username = '%s' AND " .
"
password = '%s';",
$username, crypt($password, $username));
$results = mysql_query($query);
if (mysql_num_rows($results) == 1) {
$result = mysql_fetch_array($results);
$user_id = $result['user_id'];
// setcookie
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;
header("Location: show_user.php");
exit();
} else {
// ,
$error_message = " -.";
}
}

,
$_SESSION, .
, .
, ?



- . ,
. , . , .13.1
, . -
?
signin.php.
? , .
show_user.php, signin.php.
authorize_user, authorize.php.
show_user.php:
<?php
require '../scripts/authorize.php';
require '../scripts/database_connection.php';
require '../scripts/view.php';
//
authorize_user();

13.

497

. authorize_user
$_COOKIE,
$_REQUEST.
<?php
require_once 'database_connection.php';
require_once 'app_config.php';
function authorize_user($groups = NULL) {
// cookie-,
if ((!isset($_COOKIE['user_id'])) || (!strlen($_COOKIE['user_id']) > 0)) {
header('Location: signin.php?' .
'error_message= .');
exit();
}
// ....

. $_COOKIE
$_SESSION:
<?php
require_once 'database_connection.php';
require_once 'app_config.php';
function authorize_user($groups = NULL) {
// ,
if ((!isset($_SESSION['user_id'])) || (!strlen($_SESSION['user_id']) > 0)) {
header('Location: signin.php?' .
'error_message= .');
exit();
}
// . ...


, :
//
$query_string =
"SELECT ug.user_id" .
" FROM user_groups ug, groups g" .
" WHERE g.name = '%s'" .
"
AND g.id = ug.group_id" .
"
AND ug.user_id = " . mysql_real_escape_string($_SESSION['user_id']);

. , ,
. ,
(.13.6). ?

498

4.

. 13.6. $_COOKIE $_SESSION,

. .
.

- session_start.
, .
, , , signin.php. PHP , - .
show_user.php , signin.php.
,
- Wi-Fi Ethernet.
?
: start_session
cookie-. , cookie-!
cookie- - (.13.7).
, . : . , .

13.

499

. 13.7. cookie- ,
-

, , . cookie- , ,
, . , , $_SESSION,
session_start.
, show_user.php
. session_start
authorize.php, authorize_
user authorize.php.
<?php
require_once 'database_connection.php';
require_once 'app_config.php';
session_start();
function authorize_user($groups = NULL) {
// . ...
}
?>

500

4.

, , . , .13.8,
.

. 13.8.

. ?
- , , ,
.

$_REQUEST
$_SESSION
show_user.php, :
// ID ,
$user_id = $_REQUEST['user_id'];

, ,
: $_REQUEST, $_GET, $_POST $_COOKIE.
$_REQUEST. -

13.

501

, $_REQUEST, $_SESSION.
, show_users.php ,
:
$user_row = sprintf(
"<li><a href='show_user.php?user_id=%d'>%s %s</a> " .
"(<a href='mailto:%s'>%s</a>) " .
"<a href='javascript:delete_user(%d);'><img " .
"class='delete_user' src='../images/delete.png' " .
"width='15' /></a></li>",
$user['user_id'], $user['first_name'], $user['last_name'],
$user['email'], $user['email'], $user['user_id']);
echo $user_row;

- show_users.php. while,
HTML.

, $_REQUEST $_SESSION
, . , , $_SESSION, $_REQUEST:
<?php
require '../scripts/authorize.php';
require '../scripts/database_connection.php';
require '../scripts/view.php';
//
authorize_user();
// ID ,
$user_id = $_REQUEST['user_id'];
if (!isset($user_id)) {
$user_id = $_SESSION['user_id'];
}
// $user_id

, $_REQUEST,
$_SESSION.
session_start:
<?php
require '../scripts/authorize.php';

502

4.

require '../scripts/database_connection.php';
require '../scripts/view.php';
session_start();
//
authorize_user();
// ID ,
$user_id = $_REQUEST['user_id'];
if (!isset($user_id)) {
$user_id = $_SESSION['user_id'];
}
// $user_id

, -, .

show_user.php session_start :
authorize.php, require_once,
show_user.php.
, PHP
, , ,
authorize.php, session_start. ,
, show_user.php, .
. session_start ,
- .

?
. -
$_COOKIE, , .
session_start:
<?php
require_once 'app_config.php';
require_once 'authorize.php';
define("SUCCESS_MESSAGE", "success");
define("ERROR_MESSAGE", "error");
session_start();
// ...
?>

13.

503

display_title $_COOKIE $_SESSION:


function display_title($title, $success_message = NULL, $error_message = NULL)
{
echo <<<EOD
<body>
<div id="page_start">
<div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
<div id="example">$title</div>
<div id="menu">
<ul>
<li><a href="index.html"> </a></li>
EOD;
if (isset($_SESSION['user_id'])) {
if (user_in_group($_COOKIE['user_id'], "Administrators")) {
echo "<li><a href='show_users.php'></a></li>";
}
echo "<li><a href='show_user.php'></a></li>";
echo "<li><a href='signout.php'> </a></li>";
} else {
echo "<li><a href='signin.php'></a></li>";
}
echo <<<EOD
</ul>
</div>
EOD;
display_messages($success_message, $error_message);
echo "</div> <!-- , id="page_start -->";
}

, , .
. , .


.
cookie- . $_SESSION, unset.
$_SESSION,
session_start (
unset). signout.php :
<?php
session_start();
unset($_SESSION['user_id']);

504

4.

unset($_SESSION['username']);
header('Location: signin.php');
exit();
?>

cookie- ,
signout.php, .
, 20 , cookie . .
.

?
. , 7
(
PHP
)? error_message show_error.php.

:
if (isset($_REQUEST['error_message'])) {
$error_message = preg_replace("/\\\\/", '', $_REQUEST['error_message']);
} else {
$error_message = " - .";
}

scripts/show_error.php.

, URL :
http://yellowtagmedia.com/phpMM/ch07/show_error.php?error_message=
%3Ca%20href=%22http://www.syfy.com/beinghuman%22%3E%20,
%20%20%20%20%3C/a%3E

, .13.9. ,
, .
, ,
. , . , ,
. , ,
.

13.

505

. 13.9. - CSS-,
,

scripts/app_config.php handle_
error:
function handle_error($user_error_message, $system_error_message) {
header("Location: " . get_web_path(SITE_ROOT) .
"scripts/show_error.php?" .
"error_message={$user_error_message}&" .
"system_error_message={$system_error_message}");
header("Location: " . get_web_path(SITE_ROOT) . "scripts/show_error.php");
exit();
}

PHP-
. :
function handle_error($user_error_message, $system_error_message) {
session_start();

506

4.

$_SESSION['error_message'] = $user_error_message;
$_SESSION['system_error_message'] = $system_error_message;
header("Location: " . get_web_path(SITE_ROOT) . "scripts/show_error.php");
exit();
}

. handle_error
.
show_error.php
:
<?php
require 'app_config.php';
session_start();
if (isset($_SESSION['error_message'])) {
$error_message = preg_replace("/\\\\/", '', $_SESSION['error_message']);
} else {
$error_message = " - .";
}
if (isset($_SESSION['system_error_message'])) {
$system_error_message = preg_replace("/\\\\/", '',
$_SESSION['system_error_message']);
} else {
$system_error_message =" .";
}
?>

HTML, PHP, .

URL,
show_error.php ( scripts/). URL
:
http://www.yellowtagmedia.com/phpMM/scripts/show_error.php?error_message=
%3Ca%20href=%22http://www.syfy.com/beinghuman%22%3E%20,
%20%20%20%20%3C/a%3E

,
.

. ,
, .13.10.

13.

507

. 13.10.

. , URL.
.


cookie-?
, .
. , , .
. ,
,
cookie-.
,
cookie
- , .

508

4.

cookie- .

.
, ,
.
, ,
, .
. ,
. , ... .

.
PHP MySQL.
.

.
.
.
.
.
.

, 198206, -, , 73, . 29.


005-93, 2; 95 3005 .
24.07.12. 70100/16. . . . 41,280. 2000. 0000.
.
180004, , . , 34.

?
!
?
?
? ,

?
!


!

www.piter.com/ePartners

www.piter.com,
,

( www.piter.com)
!
.
10% ,
, - c
. ,
, 5%
.
, , 500 ,
. Web.Money.
:
http://www.piter.com/book.phtml?978538800282
http://www.piter.com/book.phtml?978538800282&refer=0000
, 0000


WWW.PITER.COM