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.. − Với MySQL, chúng ta có thể truy vấn một cơ sở dữ li
Trang 1PHÁT TRIỂN ỨNG DỤNG WEB
Bài 3:
PHP Database
Nguyễn Hữu Thể
Trang 2Nộ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 Delete
▪ MySQL & Font Unicode
Trang 3PHP 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":
Trang 4Queries
− 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:
Trang 5PHP 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.
Trang 6Create a Table
− CREATE TABLE : tạo ra một bảng trong MySQL.
Ví dụ: tạo table MyGuest:
CREATE TABLE MyGuests (
id INT AUTO_INCREMENT PRIMARY KEY,firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,email VARCHAR(50),
reg_date TIMESTAMP)
AUTO_INCREMENT :
tự động tăng giá trị của field lên 1 mỗi khi một record mới được thêm vào
Trang 7PHP MySQL Insert Into
− Không xác định tên cột dữ liệu được chèn vào, chỉ đưa vào giá trị
− Quy định cụ thể cả các tên cột và các giá trị sẽ được chèn vào
VALUES (value1, value2, value3, )
Ví dụ:
Trang 9PHP 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.
SELECT id, firstname, lastname FROM MyGuests
Trang 10PHP 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.
Trang 13SELECT * FROM MyGuests LIMIT 30
SELECT * FROM MyGuests LIMIT 15, 10
Trang 14PHP MySQL Connect to a Database
− PHP 5 and later can work with a MySQL database using:
▪ MySQL i extension (the "i" stands for improved)
▪ PDO (PHP Data Objects)
▪ 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.
Trang 15MySQLi and PDO
− Three ways of working with PHP and MySQL:
▪ MySQLi (object-oriented)
▪ MySQLi (procedural)
Trang 17Open a Connection to MySQL
echo "Connected successfully";
}catch(PDOException $e){
Trang 18Close the Connection
− The connection will be closed automatically when the
script ends To close the connection before, use the
Trang 19MySQL & Font Unicode
Encode
Decode
Trang 20$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
Trang 21$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')" ;
Trang 22$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){
Trang 23// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " $row[ "id" ] " - Name: " $row[ "firstname" ] " " $row[ "lastname" ] "<br>" ;
}
} else {
Trang 24// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " $row[ "id" ] " - Name: " $row[ "firstname" ] " " $row[ "lastname" ] "<br>" ;
Trang 25$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 "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" $row[ "id" ] "</td><td>" $row[ "firstname" ] " " $row[ "lastname" ] "</td></tr>" ;
Trang 29echo "Error updating record: " $conn->error;
PHP Update Data in MySQL (MySQLi Object-oriented)
Trang 30// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() " records UPDATED successfully" ;
} catch (PDOException $e) { echo $sql "<br>" $e->getMessage(); }
$conn = null;
?>
PHP Update Data in MySQL (PDO)
Trang 31- 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
Trang 32Họ: < input type = "text" name = "lastname" />
Tên: < input type = "text" name = "firstname" />
Email: < input type = "text" name = "email" />
< input type = "submit" value = " Lưu " />
</ pre >
</ form >
</ body >
Trang 33PHP & MySQL
process-add-myguest.php
<?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 (mysql i _query($conn, $sql)) {
echo "Success" ;
} else {
Trang 34PHP & MySQL
Dữ liệu mẫu đã thêm vào table MyGuests
Trang 35PHP & MySQL