I am using variables from config file to establish sql connection on my php files. Connection works fine in those files but to make the website more organized I decided to have one file for connection. I got the code from the internet, the connection does not worked. giving me this error:
' Error: Connect failed: Access denied for user 'something'@'server.com' (using password: NO)'
The user info at the config file is different and the password is set.
This is the details: My website like this structure:
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.
in the config.ini
[database]
username = someone
password = something
dbname = something
in db_functions.php file
<?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;
}
?>
in 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';
?>
Those cods have error: Error: Connect failed: Access denied for user 'something'@'server.com' (using password: NO)
However when I copied the same function from db_functions.php file to loginCode.php file and change this line $config = parse_ini_file('../config.ini');
to $config = parse_ini_file('../../config.ini');
, it works perfectly and the connection success.
Also it works without error when I replaced the connection variables in db_functions.php by the actual database user information, calling the function from loginCode.php.
I think there is a problem on db_functions.php who can not assess information in config file but why the other files can access it?
update: I moved loginCode.php file to public_html folder connection works. and I moved db_functions.php file to admin folder it worked also.