php 初階課程 part. 5 - mysqli with php, basic crud

22
PHP 初階 - 課程五 Benson Lu 2015

Upload: li-wei-lu

Post on 19-Jul-2015

240 views

Category:

Software


4 download

TRANSCRIPT

PHP 初階 - 課程五 Benson Lu

2015

OVERVIEWUsing database with MySQLi

CRUD

CRUD

Create - Read - Update - Delete新增 讀取 修改 刪除

What is Database資料庫

A database is an organized collection of data.

DatabaseTABLE

How Does My Data Get Stored? Ans: tables

Databases use a series of Tables to store the data.

first name

last name email

Benson Lu [email protected]

Cherry Lin [email protected]

#_asukademy_users

Databaseid

How Do I Organize My Data? Ans: id

For each record, we give a

id first name

last name email

1 Benson [email protected]

m

2 Cherry Lin [email protected]

#__asukademy_users

unique id (Primary key)

Database

One database may have multiple tables

id first name

last name email

1 Benson Lu [email protected]

2 Cherry Lin [email protected]

#__asukademy_users

id city area

3 Taichung South

4 Taipei Xinyi

#__asukademy_address

Database

Table may have relation with other tables

id first name

last name email addres

s_id

1 Benson Lu

llwbenson@gmail.

com4

2 Cherry Lin [email protected] 3

#__asukademy_users

id city area

3 Taichung South

4 Taipei Xinyi

#__asukademy_addresses

Create your DatabaseCREATE

Create your DatabasePlan your table

1. decide what information you want to store 2. decide what TYPE is that data ex: date, varchar, char, 3. create table 4. create table structure

Table data TYPEType

Table data TYPEType

型態 空間需求 範圍

TINYINT 1 Signed: -128 to 127 Unsigned: 0 to 255

INT 4 Signed: -2147683648~2147683647 Unsigned: 0~4294967295

DATE 3 1000-01-01~9999-12-31

CRUD

Create - Read - Update - Delete新增 讀取 修改 刪除

File Structuremysqli.php

Database 物件, 拿來與 mysqli 做連線,下指令create.php

update.phpdelete.php

接收使⽤用者指令,並使⽤用 db 物件操作資料庫list.php

item.php

顯⽰示畫⾯面

update.php

Connect to Databasemysqli($host, $username, $password, $db_name)

Read from DatabaseSELECT * FROM user

1. Make connection2. SELECT * from table_name3. execute query4. parse result($result->num_rows)5. Close connection

Read from DatabaseSELECT * FROM user

Create from DatabaseINSERT INTO table (column1, column2, …)

VALUE(NULL, val2, val3, …)

1. Make connection2. INSERT INTO FOO3. execute query4. Close connection

Update from Database

1. We must have ID to determine which record to modified

2. We must know the what columns to update3. Make connection4. UPDATE table SET foo=bar …….. WHERE id=?5. execute query6. Close Connection

UPDATE table_name SET `column1`=`val1` … WHERE `id`=3

Update to Database

Delete from Database

1. We must have ID to determine which record to delete

2. Make connection 3. DELETE FROM users WHERE id = ?4. execute query5. Close Connection

Thank You