3. 3
Kết nối cơ sở dữ liệu với PHP:
o MySQLi (procedural)
o MySQLi (object-oriented)
o PDO (PHP Data Objects)
▪ Laravel kết nối đến nhiều loại database qua PDO (Mysql, SQL
server, sqllite,….)
5. https://laravel.com/
5
▪ Query Builder cung cấp interface (Class – method) tương tác với cơ
sở dữ liệu
▪ Để sử dụng query builder thông qua class DB
▪ Sử dụng lệnh bên dưới trước khi dùng DB:
Tìm hiểu về Quey Builder
use IlluminateSupportFacadesDB;
6. https://laravel.com/
6
Cấu hình kết nối database
▪ Trong File .env
▪ DB_HOST : địa chỉ server chứa mysql
▪ DB_PORT: port của database server Mysql (default 3306)
▪ DB_DATABASE: têndatabase
▪ DB_USERNAME: username kết nối database
▪ DB_PASSWORD: mật khẩu để kết nối database
Query Builder
7. https://laravel.com/
7
Query lấy dữ liệu trong table
❑ Lấy tất cả dữ liệu trong 1 table
▪ DB::table('tableName')
=> Tạo query : Select * from tableName
Query Builder
=> Dùng phương thức get để lấy ra dữ liệu của câu truy vấn
▪ DB::table('tableName')->get()
13. https://laravel.com/
13
Query lấy dữ liệu trong table
❑ Xác định các column sẽ lấy trong table và đặt
bí danh cho column
Query Builder
DB::table('tableName')
->select('colName1 as newName', 'colName2', 'colNameN')
->get()
31. https://laravel.com/
31
Query lấy dữ liệu trong table
Query Builder
=> Dùng phương thức get để lấy danh sách các row từ thực thi câu truy vấn
DB::table('tableName’)
->….
->get()
DB::table('tableName’)
->….
->first()
=> Dùng phương thức first để lấy row đầu tiên từ thực thi câu truy vấn
35. https://laravel.com/
35
Query lấy dữ liệu trong table
Query Builder
❑ Kiểm tra sự tồn tại của dữ liệu
▪ isEmpty()
=> trả về true nếu không có bản ghi nào trong Collection
=> nếu có thì trả false
▪ isNotEmpty() : ngược lại
36. https://laravel.com/
36
Query lấy dữ liệu trong table
Query Builder
❑ Một số phương thức khác
Xem thêm tại
https://laravel.com/docs/10.x/queries
https://laravel.com/docs/<version mới nhất>/queries
▪ max
▪ min
▪ avg
▪ sum
▪ …………..
▪ distinct
▪ groupBy
▪ having