在 Ubuntu 上使用 ThinkPHP 连接数据库,通常步骤如下(以 ThinkPHP 6 为例,5.1 类似):
sudo apt update
sudo apt install php-mysql
安装后重启服务:
sudo systemctl restart php-fpm
# 或
sudo systemctl restart apache2
ThinkPHP 的数据库配置文件在:
config/database.php
return [
// 数据库类型
'type' => 'mysql',
// 服务器地址
'hostname' => '127.0.0.1',
// 数据库名
'database' => 'test_db',
// 用户名
'username' => 'root',
// 密码
'password' => 'your_password',
// 端口
'hostport' => '3306',
// 字符集
'charset' => 'utf8mb4',
];
use think\facade\Db;
$list = Db::table('user')->select();
print_r($list);
namespace app\model;
use think\Model;
class User extends Model
{
protected $table = 'user';
}
调用:
$user = \app\model\User::find(1);
sudo systemctl status mysql
sudo ufw allow 3306
GRANT ALL PRIVILEGES ON test_db.* TO 'root'@'localhost';
FLUSH PRIVILEGES;
如果是远程数据库:
'hostname' => '远程IP',
并确保:
CREATE USER 'user'@'%' IDENTIFIED BY 'password';
GRANT ALL ON db.* TO 'user'@'%';
如果你用的是 ThinkPHP 5.1 / 8.0 / 特定版本,或者连接的是 SQLite / PostgreSQL,可以告诉我,我可以给你对应配置示例。