在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;
?>
确保在尝试连接之前,你已经正确配置了数据库服务器的详细信息,并且数据库用户具有适当的权限。