在PHP中,可以使用MySQLi或PDO擴展來查詢數據庫中的數據。以下是兩種方法的示例:
方法1:使用MySQLi擴展
mydb
的數據庫的示例:$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "mydb";
// 創建連接
$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
mysqli_query()
函數執行SQL查詢,并獲取結果:$sql = "SELECT id, name, email FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// 輸出數據
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 結果";
}
mysqli_close($conn);
方法2:使用PDO擴展
mydb
的數據庫的示例:$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "mydb";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 設置 PDO 錯誤模式為異常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "連接失敗: " . $e->getMessage();
}
PDO::query()
方法執行SQL查詢,并獲取結果:$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
if ($result->rowCount() > 0) {
// 輸出數據
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 結果";
}
$conn = null;
以上示例展示了如何使用MySQLi和PDO擴展在PHP中查詢數據庫數據。請根據您的實際情況修改代碼中的數據庫連接信息和SQL查詢。