ubuntu

ubuntu中php-fpm与mysql如何连接

小樊
47
2025-09-27 10:49:13
栏目: 云计算

在Ubuntu系统中,PHP-FPM(FastCGI Process Manager)与MySQL数据库的连接通常通过PHP的MySQLi或PDO扩展来实现。以下是详细的步骤和示例代码,帮助你完成PHP-FPM与MySQL的连接。

1. 安装必要的软件包

首先,确保你已经安装了PHP和MySQL服务器。如果没有安装,可以使用以下命令进行安装:

sudo apt update
sudo apt install php-fpm mysql-server php-mysql

2. 配置PHP-FPM

确保PHP-FPM配置正确。通常情况下,Ubuntu会自动配置好PHP-FPM。你可以通过以下命令检查PHP-FPM的状态:

sudo systemctl status php7.4-fpm

如果需要重启PHP-FPM服务,可以使用以下命令:

sudo systemctl restart php7.4-fpm

3. 编写PHP脚本连接MySQL

创建一个PHP文件(例如connect.php),并编写以下代码来连接MySQL数据库:

使用MySQLi扩展

<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}
echo "连接成功";

// 关闭连接
$conn->close();
?>

使用PDO扩展

<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

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;
?>

4. 配置Web服务器

确保你的Web服务器(如Apache或Nginx)已经配置好,并且能够处理PHP文件。

Apache配置

如果你使用的是Apache,确保启用了PHP模块:

sudo a2enmod php7.4
sudo systemctl restart apache2

Nginx配置

如果你使用的是Nginx,确保配置了PHP-FPM:

server {
    listen 80;
    server_name your_domain.com;

    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;
    }

    location ~ /\.ht {
        deny all;
    }
}

然后重启Nginx服务:

sudo systemctl restart nginx

5. 测试连接

将你的PHP文件上传到Web服务器的根目录(例如/var/www/html),然后通过浏览器访问该文件,查看是否能够成功连接到MySQL数据库。

例如,如果你上传了connect.php文件,可以通过以下URL访问:

http://your_domain.com/connect.php

如果一切配置正确,你应该会看到“连接成功”的消息。

通过以上步骤,你应该能够在Ubuntu系统中成功配置PHP-FPM与MySQL的连接。

0
看了该问题的人还看了