在PHP的LNMP(Linux, Nginx, MySQL, PHP)環境中處理數據庫連接通常涉及以下幾個步驟:
sudo systemctl status mysql
如果MySQL服務沒有運行,你可以使用以下命令來啟動它:
sudo systemctl start mysql
CREATE DATABASE mydatabase;
CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypassword';
GRANT ALL PRIVILEGES ON mydatabase.* TO 'myuser'@'localhost';
FLUSH PRIVILEGES;
sudo apt-get install php-mysql
對于PDO,你可以安裝相應的驅動程序,例如php-mysql
或php-pdo-mysql
:
sudo apt-get install php-mysql
<?php
$servername = "localhost";
$username = "myuser";
$password = "mypassword";
$dbname = "mydatabase";
// 創建連接
$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
echo "連接成功";
$conn->close();
?>
<?php
$servername = "localhost";
$username = "myuser";
$password = "mypassword";
$dbname = "mydatabase";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 設置 PDO 錯誤模式為異常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "連接成功";
} catch(PDOException $e) {
echo "連接失敗: " . $e->getMessage();
}
// 關閉連接
$conn = null;
?>
確保在嘗試連接之前,你已經正確配置了數據庫服務器的詳細信息,并且數據庫用戶具有適當的權限。