PHP数组配置文件

时间:2014-02-03 21:09:15

标签: php mysql

你可能会告诉我我是新手并试图通过创建一个包含我网站所有设置的配置文件来让自己的生活更轻松。

我正在这样做,因为我正在学习并试图将我的知识推得更加困难并一遍又一遍地重复相同的代码

我创建了一个名为settings.php的文件,我目前的代码就是这个

<?php

return array(
    'host' => 'localhost',
    'username' => 'me',
    'password' => 'password',
    'db_name' => 'mydb'
);

?>

在我的页面中我输入了以下代码

<?php
//set connection variables
$host = include('settings.php');
$username = include('settings.php');
$password = include('settings.php');
$db_name = include('settings.php');

//connect to mysql server
$mysqli = new mysqli($host, $username, $password, $db_name);

//check if any connection error was encountered
if(mysqli_connect_errno()) {
    echo "Error: Could not connect to database.";
    exit;
}
?>

我从另一个可以找到here

的问题中获取此代码

这种接缝不起作用,但我不能确定它不会出错。

在我继续这之前我想添加其他设置将存储在数据库中这是我这样做的最佳方式吗?

3 个答案:

答案 0 :(得分:3)

以下是您使用代码的方式......

<?php
//set connection variables
$config = include('settings.php');

//connect to mysql server
$mysqli = new mysqli($config['host'], $config['username'], $config['password'], $config['db_name']);

//check if any connection error was encountered
if(mysqli_connect_errno()) {
    echo "Error: Could not connect to database.";
    exit;
}
?>

答案 1 :(得分:0)

它没有给出错误,因为这是所有有效的代码,但它没有按照您的想法进行。通常,您只需在页面顶部包含一个脚本,然后在执行包含的页面中提供该脚本中定义的任何变量。

includeMe.php

<?php
$settings = array(
    'host' => 'localhost',
    'username' => 'me',
    'password' => 'password',
    'db_name' => 'mydb'
);

pageThatNeedsSettings.php

<?php
include("includeMe.php");
//now the settings variable is available to be used
echo $settings['host']; //outputs: localhost

答案 2 :(得分:0)

使用您的方法有几种方法,但这里有一个:

$settings = include('settings.php');
$username = $settings['username'];
//etc..

但是,只是放弃回报业务并执行此操作:

$settings = array(
    'host' => 'localhost',
    'username' => 'me',
    'password' => 'password',
    'db_name' => 'mydb'
);

使用include中的$settings

include('settings.php');
$username = $settings['username'];
//etc..

或者我会在需要时使用$settings['username'],而不是将其分配给$username

$mysqli = new mysqli($settings['host'], $settings['username'], $settings['password'], $settings['db_name']);