温馨提示×

PHP中保存数据库连接信息的方式

PHP
小樊
113
2024-09-07 16:41:04
栏目: 编程语言
亿速云云数据库,读写分离,安全稳定,弹性扩容,低至0.3元/天!! 点击查看>>

在 PHP 中,保存数据库连接信息的常用方法有以下几种:

  1. 使用配置文件(如 .ini 或 .php 文件):

创建一个单独的配置文件,例如 config.phpconfig.ini,并将数据库连接信息保存在其中。然后,在需要连接到数据库的脚本中,引入这个配置文件。

示例(config.php):

<?php
$db_host = "localhost";
$db_username = "your_username";
$db_password = "your_password";
$db_name = "your_database_name";
?>

在需要连接到数据库的脚本中,引入配置文件:

<?php
require_once 'config.php';

// 使用变量创建 PDO 或 MySQLi 连接
$dsn = "mysql:host=$db_host;dbname=$db_name";
$conn = new PDO($dsn, $db_username, $db_password);
?>
  1. 使用常量:

在配置文件中定义常量,然后在需要连接到数据库的脚本中引入该配置文件。

示例(config.php):

<?php
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'your_username');
define('DB_PASSWORD', 'your_password');
define('DB_NAME', 'your_database_name');
?>

在需要连接到数据库的脚本中,引入配置文件:

<?php
require_once 'config.php';

// 使用常量创建 PDO 或 MySQLi 连接
$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
$conn = new PDO($dsn, DB_USERNAME, DB_PASSWORD);
?>
  1. 使用数组:

在配置文件中定义一个包含数据库连接信息的数组,然后在需要连接到数据库的脚本中引入该配置文件。

示例(config.php):

<?php
$db_config = array(
    'host' => 'localhost',
    'username' => 'your_username',
    'password' => 'your_password',
    'name' => 'your_database_name'
);
?>

在需要连接到数据库的脚本中,引入配置文件:

<?php
require_once 'config.php';

// 使用数组创建 PDO 或 MySQLi 连接
$dsn = "mysql:host=" . $db_config['host'] . ";dbname=" . $db_config['name'];
$conn = new PDO($dsn, $db_config['username'], $db_config['password']);
?>

注意:为了安全起见,请确保将配置文件存储在不可公开访问的目录中,并遵循最佳实践来保护敏感信息。

亿速云「云数据库 MySQL」免部署即开即用,比自行安装部署数据库高出1倍以上的性能,双节点冗余防止单节点故障,数据自动定期备份随时恢复。点击查看>>

推荐阅读:PHP MVC框架的数据库连接方式

0