Dữ liệu chọn PHP MySQL
Chọn dữ liệu từ cơ sở dữ liệu MySQL
Câu lệnh SELECT được sử dụng để chọn dữ liệu từ một hoặc nhiều bảng:
SELECT column_name(s)
FROM table_name
hoặc chúng ta có thể sử dụng ký tự * để chọn TẤT CẢ các cột từ một bảng:
SELECT *
FROM table_name
Để tìm hiểu thêm về SQL, vui lòng truy cập hướng dẫn SQL của chúng tôi .
Chọn dữ liệu với MySQLi
Ví dụ sau đây chọn các cột id, họ và tên từ bảng MyGuests và hiển thị nó trên trang:
Ví dụ (MySQLi Hướng đối tượng)
<?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();
?>
Các dòng mã để giải thích từ ví dụ trên:
Đầu tiên, chúng tôi thiết lập một truy vấn SQL chọn các cột id, họ và tên từ bảng MyGuests. Dòng mã tiếp theo chạy truy vấn và đặt dữ liệu kết quả vào một biến được gọi là $ result.
Sau đó, hàm num_rows()
kiểm tra xem có nhiều hơn 0 hàng được trả về hay không.
Nếu có nhiều hơn 0 hàng được trả về, hàm fetch_assoc()
sẽ đặt tất cả kết quả vào một mảng kết hợp mà chúng ta có thể lặp qua. Vòng while()
lặp lặp qua tập kết quả và xuất dữ liệu từ các cột id, họ và tên.
Ví dụ sau cho thấy giống như ví dụ trên, theo cách thủ tục MySQLi:
Ví dụ (Thủ tục MySQLi)
<?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);
?>
Bạn cũng có thể đặt kết quả trong một bảng HTML:
Ví dụ (MySQLi Hướng đối tượng)
<?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) {
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>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
Chọn dữ liệu với PDO (+ Câu lệnh chuẩn bị)
Ví dụ sau sử dụng các câu lệnh đã chuẩn bị sẵn.
Nó chọn các cột id, họ và tên từ bảng MyGuests và hiển thị nó trong bảng HTML:
Ví dụ (PDO)
<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";
class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
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(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>