在Ubuntu上配置PHP数据库连接,通常涉及以下几个步骤:
安装PHP和数据库服务器:
sudo apt update && sudo apt install php php-cli php-mysql
sudo apt update && sudo apt install mysql-server
配置MySQL数据库:
sudo systemctl start mysql
sudo mysql_secure_installation
mysql -u root -p
CREATE DATABASE mydatabase;
CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypassword';
GRANT ALL PRIVILEGES ON mydatabase.* TO 'myuser'@'localhost';
FLUSH PRIVILEGES;
EXIT;
配置PHP连接数据库:
connect.php
。mysqli
扩展连接到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 "连接成功";
?>
测试连接:
connect.php
文件上传到你的Web服务器目录(例如/var/www/html
)。http://your_server_ip/connect.php
,如果看到“连接成功”的消息,说明配置正确。配置PHP-FPM(如果使用Nginx):
sudo apt install php-fpm
/etc/nginx/sites-available/default
),添加以下内容:server {
listen 80;
server_name your_server_ip;
root /var/www/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 根据你的PHP版本调整
}
location ~ /\.ht {
deny all;
}
}
sudo systemctl restart nginx
防火墙配置:
sudo ufw allow 'Nginx Full'
通过以上步骤,你应该能够在Ubuntu上成功配置PHP数据库连接。
亿速云「云数据库 MySQL」免部署即开即用,比自行安装部署数据库高出1倍以上的性能,双节点冗余防止单节点故障,数据自动定期备份随时恢复。点击查看>>
相关推荐:PHP在Ubuntu上的数据库连接配置