Câu lệnh SELECT được sử dụng để truy xuất dữ liệu từ một hoặc nhiều bảng:
SELECT column_name(s)
FROM table_name
Ví dụ sau đây truy xuất các cột id, firstname và lastname từ bảng MyGuests và hiển thị nó trên trang:
<?php
$servername = "localhost";
$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 = "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"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Đây là kết quả:
id: 1 - Name: John Doe
id: 2 - Name: Mary Moe
id: 3 - Name: Julie Dooley
Đầu tiên, chúng tôi tạo một truy vấn SQL truy xuất các cột id, firstname và lastname từ bảng MyGuests. Dòng mã tiếp theo sẽ thực thi truy vấn và lưu dữ liệu kết quả vào biến $result
.
Sau đó, hàm num_rows()
sẽ kiểm tra có dữ liệu trả về hay không.
Nếu có thì hàm fetch_assoc()
sẽ gán tất cả kết quả vào một mảng kết hợp mà chúng ta có thể duyệt qua. Vòng lặp while()
sẽ duyệt qua tập kết quả rồi hiển thị các cột id, firstname và lastname lên trang.
Ví dụ sau đây tương tự như ví dụ trên, nhưng nó sử dụng MySQLi thủ tục:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
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"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Đây là kết quả:
id: 1 - Name: John Doe
id: 2 - Name: Mary Moe
id: 3 - Name: Julie Dooley
Ví dụ sau sử dụng PDO để truy xuất dữ liệu.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt->fetchAll() as $row) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>
Đây là kết quả:
id: 1 - Name: John Doe
id: 2 - Name: Mary Moe
id: 3 - Name: Julie Dooley
Mệnh đề WHERE được sử dụng để lọc những bản ghi đáp ứng một điều kiện cụ thể.
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
Ví dụ sau đây truy xuất các cột id, firstname và lastname từ bảng MyGuests những người có họ là "Doe" và hiển thị nó trên trang:
<?php
$servername = "localhost";
$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 = "SELECT id, firstname, lastname FROM MyGuests WHERE lastname='Doe'";
$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"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Đây là kết quả:
id: 1 - Name: John Doe
Đầu tiên, chúng tôi tạo truy vấn SQL truy xuất các cột id, firstname và lastname từ bảng MyGuests những người có họ là "Doe". Dòng mã tiếp theo sẽ thực thi truy vấn và lưu dữ liệu kết quả vào biến $result
.
Sau đó, hàm num_rows()
sẽ kiểm tra có dữ liệu trả về hay không.
Nếu có thì hàm fetch_assoc()
sẽ gán tất cả kết quả vào một mảng kết hợp mà chúng ta có thể duyệt qua. Vòng lặp while()
sẽ duyệt qua tập kết quả rồi hiển thị các cột id, firstname và lastname lên trang.
Ví dụ sau đây tương tự như ví dụ trên, nhưng nó sử dụng MySQLi thủ tục:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM MyGuests WHERE lastname='Doe'";
$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"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Đây là kết quả:
id: 1 - Name: John Doe
Ví dụ sau sử dụng PDO để truy xuất dữ liệu.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests WHERE lastname='Doe'");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt->fetchAll() as $row) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>
Đây là kết quả:
id: 1 - Name: John Doe
Câu lệnh ORDER BY được sử dụng để sắp xếp các bản ghi theo thứ tự tăng dần (ASC) theo mặc định. Để sắp xếp các bản ghi theo thứ tự giảm dần, hãy sử dụng từ khóa DESC.
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC
Ví dụ sau đây truy xuất các cột id, firstname và lastname từ bảng MyGuests theo thứ tự lastname tăng dần và hiển thị nó trên trang:
<?php
$servername = "localhost";
$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 = "SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname ASC";
$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"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Đây là kết quả:
id: 1 - Name: John Doe
id: 3 - Name: Julie Dooley
id: 2 - Name: Mary Moe
Đầu tiên, chúng tôi tạo một truy vấn SQL truy xuất các cột id, firstname và lastname từ bảng MyGuests theo thứ tự lastname tăng dần. Dòng mã tiếp theo sẽ thực thi truy vấn và lưu dữ liệu kết quả vào biến $result
.
Sau đó, hàm num_rows()
sẽ kiểm tra có dữ liệu trả về hay không.
Nếu có thì hàm fetch_assoc()
sẽ gán tất cả kết quả vào một mảng kết hợp mà chúng ta có thể duyệt qua. Vòng lặp while()
sẽ duyệt qua tập kết quả rồi hiển thị các cột id, firstname và lastname lên trang.
Ví dụ sau đây tương tự như ví dụ trên, nhưng nó sử dụng MySQLi thủ tục:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname ASC";
$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"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Đây là kết quả:
id: 1 - Name: John Doe
id: 3 - Name: Julie Dooley
id: 2 - Name: Mary Moe
Ví dụ sau sử dụng PDO để truy xuất dữ liệu.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname ASC");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt->fetchAll() as $row) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>
Đây là kết quả:
id: 1 - Name: John Doe
id: 3 - Name: Julie Dooley
id: 2 - Name: Mary Moe
MySQL cung cấp mệnh đề LIMIT để chỉ định số lượng bản ghi sẽ trả về.
Mệnh đề LIMIT giúp dễ dàng giới hạn kết quả trả về hoặc phân trang bằng SQL và rất hữu ích trên các bảng lớn. Trả về quá nhiều dữ liệu trong một lần truy vấn có thể ảnh hưởng đến hiệu suất của hệ thống.
Giả sử chúng tôi muốn truy xuất tất cả các bản ghi từ 1 - 30 từ một bảng MyGuests. Truy vấn SQL sẽ trông như thế này:
SELECT id, firstname, lastname
FROM MyGuests
LIMIT 30
Khi chạy truy vấn SQL ở trên nó sẽ trả về 30 bản ghi đầu tiên.
Nếu chúng tôi muốn truy xuất 10 bản ghi tính từ bản ghi thứ 16 thì sao?
Mysql cũng cung cấp một cách để xử lý việc này đó là sử dụng từ khóa OFFSET. Ví dụ dưới đây minh họa sử dụng từ khóa OFFSET:
SELECT id, firstname, lastname
FROM MyGuests
LIMIT 10 OFFSET 15
Bạn cũng có thể sử dụng cú pháp sau cũng đạt được kết quả tương tự:
SELECT id, firstname, lastname
FROM MyGuests
LIMIT 15, 10
Lưu ý: các số được đảo ngược khi bạn sử dụng dấu phẩy.
Bạn có thể vui lòng tắt trình chặn quảng cáo ❤️ để hỗ trợ chúng tôi duy trì hoạt động của trang web.
Hướng dẫn lập trình PHP toàn tập sẽ giúp bạn từng bước tìm hiểu và nắm vững ngôn ngữ lập trình PHP.
MySQL prepared statements trong PHP rất hữu ích để chống lại các cuộc tấn công SQL Injection.
Hướng dẫn này sẽ giúp bạn tìm hiểu cách thêm dữ liệu vào MySQL sử dụng MySQLi và PDO trong PHP.
MySQL là gì? Làm việc với MySQL trong PHP. Hướng dẫn kết nối, tạo database, tạo bảng MySQL trong PHP.