首页 > 解决方案 > 从配置变量连接到 sql 导致错误(php 代码)

问题描述

我正在使用配置文件中的变量在我的 php 文件上建立 sql 连接。连接在这些文件中工作正常,但为了使网站更有条理,我决定使用一个文件进行连接。我从互联网上得到代码,连接不起作用。给我这个错误:

'错误:连接失败:用户'something'@'server.com'的访问被拒绝(使用密码:否)'

配置文件中的用户信息不同,并且设置了密码。

这是细节:我的网站喜欢这样的结构:

root ----> 1)config.ini 2)public_html folder
public_html ----> website pages including 1)db_functions.php and 2)admin folder
admin ---->login.php and loginCode.php.

在 config.ini

[database]
username = someone
password = something
dbname = something

在 db_functions.php 文件中

<?php
/**
 * Database functions for a MySQL with PHP tutorial
 * 
 * @copyright Eran Galperin
 * @license MIT License
 * @see http://www.binpress.com/tutorial/using-php-with-mysql-the-right-way/17
 */

/**
 * Connect to the database
 * 
 * @return bool false on failure / mysqli MySQLi object instance on success
 */
function db_connect() {


    // Define connection as a static variable, to avoid connecting more than once 
    static $connection;

    // Try and connect to the database, if a connection has not been established yet
    if(!isset($connection)) {
        // Load configuration as an array. Use the actual location of your configuration file
        $config = parse_ini_file('../config.ini'); 
        $connection = mysqli_connect('server',$config['username'],$config['password'],$config['dbname']);
    }

    // If connection was not successful, handle the error
    if($connection === false) {
        // Handle error - notify administrator, log to a file, show an error screen, etc.
        return mysqli_connect_error(); 
    }
    return $connection;
}
?>

在 loginCode.php

<?php

require_once('../db_functions.php');
$connection = db_connect();
      //if connection fails, stop script execution
      if (mysqli_connect_errno()) {
            $Message = "Error: " . $sql  .  "Connect failed: ". mysqli_connect_error();
        echo $Message;
      }
      else
          echo 'no error';
?>

这些鳕鱼有错误:错误:连接失败:用户'something'@'server.com'的访问被拒绝(使用密码:否)

但是,当我将相同的函数从 db_functions.php 文件复制到 loginCode.php 文件并将这一行更改$config = parse_ini_file('../config.ini');为 时$config = parse_ini_file('../../config.ini');,它可以正常工作并且连接成功。当我用实际的数据库用户信息替换 db_functions.php 中的连接变量时,它也可以正常工作,从 loginCode.php 调用该函数。

我认为 db_functions.php 存在问题,无法评估配置文件中的信息,但为什么其他文件可以访问它?

更新:我将 loginCode.php 文件移动到 public_html 文件夹连接工作。我将 db_functions.php 文件移动到管理文件夹,它也可以工作。

标签: phpmysqli

解决方案


当我将两个文件 loginCode.php 和 db_functions.php 放在同一个文件夹中时工作。


推荐阅读