Bài giảng Phát triển ứng dụng web - Bài 3: PHP Database - Nguyễn Hữu Thể
Nội dung
▪ PHP MySQL Introduction
▪ PHP MySQL Connect to a Database
▪ PHP MySQL Create Database and Tables
▪ PHP MySQL Insert Into
▪ PHP MySQL Select
▪ PHP MySQL The Where Clause
▪ PHP MySQL Order By Keyword
▪ PHP MySQL Update
▪ PHP MySQL Delete
▪ MySQL & Font Unicode
▪ MySQLi

Trang 1

Trang 2

Trang 3

Trang 4

Trang 5

Trang 6

Trang 7

Trang 8

Trang 9

Trang 10
Tải về để xem bản đầy đủ
Bạn đang xem 10 trang mẫu của tài liệu "Bài giảng Phát triển ứng dụng web - Bài 3: PHP Database - Nguyễn Hữu Thể", để tải tài liệu gốc về máy hãy click vào nút Download ở trên
Tóm tắt nội dung tài liệu: Bài giảng Phát triển ứng dụng web - Bài 3: PHP Database - Nguyễn Hữu Thể
PHÁT TRIỂN ỨNG DỤNG WEB
Bài 3:
PHP Database
Nguyễn Hữu Thể
1
Nội dung
▪ PHP MySQL Introduction
▪ PHP MySQL Connect to a Database
▪ PHP MySQL Create Database and Tables
▪ PHP MySQL Insert Into
▪ PHP MySQL Select
▪ PHP MySQL The Where Clause
▪ PHP MySQL Order By Keyword
▪ PHP MySQL Update
▪ PHP MySQL Delete
▪ MySQL & Font Unicode
▪ MySQLi
2
PHP MySQL Introduction
− MySQL là hệ cơ sở dữ liệu nguồn mở phổ biến nhất.
− Một cơ sở dữ liệu thường bao gồm một hoặc nhiều table.
▪ Mỗi table được xác định bởi một tên (ví dụ: " Customers" hoặc "
Orders").
▪ Table chứa các records (rows) với các dữ liệu.
− Ví dụ: table "Persons":
3
Queries
− Một query là một câu hỏi hoặc yêu cầu.
− Với MySQL, chúng ta có thể truy vấn một cơ sở dữ liệu để có
thông tin cụ thể và trả về một recordset.
− Xem câu truy vấn sau:
− Câu truy vấn trên chọn tất cả các dữ liệu trong cột "LastName",
và trả về một recordset như sau:
4
PHP MySQL Create Database and Tables
− Một cơ sở dữ liệu chứa một hoặc nhiều table.
❖ Create a Database
− CREATE DATABASE : tạo ra một cơ sở dữ liệu MySQL.
❖ Syntax
Ví dụ: tạo database có tên là myDB
CREATE DATABASE myDB
5
Create a Table
− CREATE TABLE : tạo ra một bảng trong MySQL.
❖ Syntax
Ví dụ: tạo table MyGuest: AUTO_INCREMENT :
CREATE TABLE MyGuests ( tự động tăng giá trị
id INT AUTO_INCREMENT PRIMARY KEY, của field lên 1 mỗi khi
firstname VARCHAR(30) NOT NULL, một record mới được
thêm vào.
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)
6
PHP MySQL Insert Into
❖ Syntax
− Không xác định tên cột dữ liệu được chèn vào, chỉ đưa vào giá trị
INSERT INTO table_name VALUES (value1, value2, value3,...)
− Quy định cụ thể cả các tên cột và các giá trị sẽ được chèn vào
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
Ví dụ:
INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘Khánh', 'Nguyễn', ‘khanh@example.com')
7
PHP MySQL Select
− Câu lệnh SELECT được sử dụng để chọn dữ liệu từ một cơ sở dữ
liệu.
❖ Syntax
8
PHP MySQL The Where Clause
− Mệnh đề WHERE được sử dụng để trích xuất các record theo
một tiêu chuẩn quy định.
❖ Syntax:
SELECT id, firstname, lastname FROM MyGuests
9
PHP MySQL Order By Keyword
− Từ khoá ORDER BY : sắp xếp dữ liệu trong một recordset.
− ORDER BY sắp xếp records theo thứ tự tăng dần (mặc định).
− Nếu muốn thứ tự giảm dần, sử dụng từ khoá DESC.
❖ Syntax:
10
PHP MySQL Update
− Câu lệnh UPDATE : sửa đổi dữ liệu trong một table.
❖ Syntax
UPDATE MyGuests SET lastname='Kiệt' WHERE id=2
11
PHP MySQL Delete
− Câu lệnh DELETE : xóa các record trong một table.
❖ Syntax
DELETE FROM MyGuests WHERE id=3
12
Limit
SELECT * FROM MyGuests LIMIT 30
SELECT * FROM MyGuests LIMIT 15, 10
13
PHP MySQL Connect to a Database
− PHP 5 and later can work with a MySQL database using:
▪ MySQLi extension (the "i" stands for improved)
▪ PDO (PHP Data Objects)
− Should I Use MySQLi or PDO?
▪ PDO will work on 12 different database systems, whereas
MySQLi will only work with MySQL databases.
▪ Both are object-oriented, but MySQLi also offers a
procedural API.
▪ Both support Prepared Statements. Prepared Statements
protect from SQL injection.
14
MySQLi and PDO
− Three ways of working with PHP and MySQL:
▪ MySQLi (object-oriented)
▪ MySQLi (procedural)
▪ PDO
15
Open a Connection to MySQL
MySQLi Object-Oriented MySQLi Procedural
<?php <?php
$servername = "localhost"; $servername = "localhost";
$username = "username"; $username = "username";
$password = "password"; $password = "password";
// Create connection // Create connection
$conn = new mysqli($servername, $conn = mysqli_connect($servername,
$username, $password); $username, $password);
// Check connection // Check connection
if ($conn->connect_error) { if (!$conn) {
die("Connection failed: " . $conn->connect_error); die("Connection failed: " . mysqli_connect_error());
} }
echo "Connected successfully"; echo "Connected successfully";
?> ?>
16
Open a Connection to MySQL
PDO
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB",
$username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
?>
17
Close the Connection
− The connection will be closed automatically when the
script ends. To close the connection before, use the
following:
▪ Example (MySQLi Object-Oriented)
• $conn->close();
▪ Example (MySQLi Procedural)
• mysqli_close($conn);
▪ Example (PDO)
• $conn = null;
18
MySQL & Font Unicode
Encode
Decode
19
Insert (MySQLi Procedural)
<?php
$servernamePHP = & "localhost" MySQL;
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Change character set to utf8
mysqli_set_charset($conn,"utf8");
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "" . mysqli_error($conn);
}
mysqli_close($conn); 20
?>
Insert (MySQLi Object-oriented)
<?php
$servername PHP= "localhost" &; MySQL
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "" . $conn->error;
}
$conn->close();
?> 21
Insert (PDO)
<?php
$servername PHP= "localhost" &; MySQL
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "New record created successfully. Last inserted ID is: " . $last_id;
}catch(PDOException $e){
echo $sql . "" . $e->getMessage();
}
$conn = null;
?> 22
Select Data With MySQLi (MySQLi Procedural)
<?php
$servername PHP= "localhost" &; MySQL
$username = "username"; //root
$password = "password"; //
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "";
}
} else {
echo "0 results";
}
mysqli_close($conn); 23
?>
Select Data With MySQLi (MySQLi Object-oriented)
<?php
$servername PHP= "localhost" &; MySQL
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "";
}
} else {
echo "0 results";
}
$conn->close(); 24
?>
Select Data With MySQLi (MySQLi Object-oriented): HTML table
<?php
$servername PHP= "localhost" &; MySQL
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "IDName";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "".$row["id"]."".$row["firstname"]." ".$row["lastname"]."";
}
echo "";
} else {
echo "0 results";
}
$conn->close();
25
?>
PHP Delete Data From MySQL (MySQLi Procedural)
<?php
$servername PHP= "localhost" &; MySQL
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
26
PHP Delete Data From MySQL (MySQLi Object-oriented)
<?php
$servername PHP= "localhost" &; MySQL
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
27
PHP Update Data in MySQL (MySQLi Procedural)
<?php
$servername PHP= "localhost" &; MySQL
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
28
PHP Update Data in MySQL (MySQLi Object-oriented)
<?php
$servername PHP= "localhost" &; MySQL
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
29
PHP Update Data in MySQL (PDO)
<?php
$servername PHP= "localhost" &; MySQL
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname",
$username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
} catch(PDOException $e) { echo $sql . "" . $e->getMessage(); }
$conn = null;
?> 30
Ví dụ
- Tạo 3 file: dbcon.php: chứa kết nối CSDL
- add-myguest.php: giao diện nhập liệu
- process-add-myguest.php: code xử lý thêm dữ liệu đã nhập
dbcon.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
mysqli_set_charset($conn,"utf8");
?>
31
add-myguest.php
Họ:
Tên:
Email:
32
processPHP-add -&myguest.php MySQL
<?php
require 'dbcon.php';
$lastname = $_POST["lastname"];
$firstname = $_POST["firstname"];
$email = $_POST["email"];
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('$lastname', '$firstname', '$email')";
if (mysqli_query($conn, $sql)) {
echo "Success";
} else {
echo "Fail";
}
mysqli_close($conn);
?> 33
PHP & MySQL
Dữ liệu mẫu đã thêm vào table MyGuests
34
− Tạo database:PHP & TinTucOnline, MySQL có diagram như hình:
35File đính kèm:
bai_giang_phat_trien_ung_dung_web_bai_3_php_database_nguyen.pdf

