在PHP中,數據庫連接通常是通過數據庫擴展來實現的,比如MySQL擴展、MySQLi擴展或PDO擴展。在啟動時,我們可以通過以下步驟來管理數據庫連接:
// config.php
define('DB_HOST', 'localhost');
define('DB_USER', 'username');
define('DB_PASS', 'password');
define('DB_NAME', 'database_name');
mysqli_connect()
或new PDO()
來創建數據庫連接。// connection.php
include 'config.php';
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (!$conn) {
die("Database connection failed: " . mysqli_connect_error());
}
// query.php
include 'connection.php';
$query = "SELECT * FROM users";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "User: " . $row['username'] . "<br>";
}
} else {
echo "No users found";
}
mysqli_close($conn);
// query.php
mysqli_close($conn);
通過以上步驟,我們可以在PHP啟動時有效地管理數據庫連接,并在需要時執行數據庫操作。同時,我們還可以考慮使用連接池或ORM框架來更好地管理數據庫連接和操作。