我想保留一个文件的PHP连接,而不是每个页面上使用mysqli_connect。PHP Funcition和数据库连接
我有具有Db的凭据的config.ini文件,该文件I在PHP文件db_connect.php db_connect.php的代码调用低于:
//stores hostname or the server name
$hostName;
//username for the database
$userName;
//password for the database
$password;
//database name
$dbName;
$ini = parse_ini_file('../../config/config.ini');
while(list($key,$value) = each($ini))
{
if($key == 'hostName')
{
$hostName = $value; //retrieving value of host name.
}
else if($key == 'userName')
{
$userName = $value; //retrieving database user name
}
else if($key == 'password')
{
$password = $value; //retrieving database password
}
else if($key == 'dbName')
{
$dbName = $value; //retrieving database name.
}
}
$connectobject1 = new mysqli($hostName, $userName, $password, $dbName);
if ($connectobject1->connect_errno)
{
echo "Connection Failed";
exit();
}
使用上面的代码,我能够创建到数据库的连接。现在,当我在我的index.php文件中包含db_connect.php时,我使用require_once'db_connect.php',但是当index.php中的函数执行时,问题就开始了。这些函数无法访问连接字符串。我的index.php代码示例如下:
//Creating DB connection
require_once '../connect/db_connect.php';
//Checking DB connection
if(!$connectobject1)
{
//connection to DB failed
header('Location: /pages/error/error.php?id=0');
exit();
}
function checkuser($UserID, $connectobject1)
{
//function code
}
我读过,使用全局连接不是一个好习惯。
请提醒我如何继续我的连接。 谢谢。
什么的连接字符串是你在说什么?哪些功能无法访问此字符串?你怎么称呼这些功能? –
@u_mulder - 这些函数都不能连接到数据库。我这样调用函数:checkuser($ UserID,$ connectobject1) – dk007
db_connect.php文件和索引文件在同一个文件夹中? – JYoThI