M
M
Maxim Zolotoy2018-03-05 19:56:18
PHP
Maxim Zolotoy, 2018-03-05 19:56:18

Why is there an error connecting to the database?

What a nonsense. If I specify the root login directly, then it connects. And if I pass it through a variable, I get the following error Warning: mysqli_connect(): (HY000/1045): Access denied for user ''@'localhost' (using password: NO) in C:\openserver\OSPanel\domains\darkdate\ www\modules\config.php on line 9
who can tell me what's wrong?
this is how it works
5a9d7687007bd617733178.jpeg
and this is how it throws an error
5a9d76a4c793a674180945.jpeg

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Immortal_pony, 2018-03-05
@spacenear

Your variables are declared outside of the function.
There are three solutions:
1. The function must accept arguments, and when called, you will pass them ( recommended ):

function connect($server, $login, $password, $db) {
    return mysqli_connect($server, $login, $password, $db)
}

$connection = connect($server, $login, $password, $db);

2. The function will retrieve variables from the global scope:
function connect() {
    global $server;
    global $login;        
    global $password;
    global $db;

    return mysqli_connect($server, $login, $password, $db);
}

$connection = connect($server, $login, $password, $db)

3. The function will be anonymous and retrieve data from the local scope:
$connect = function() use ($server, $login, $password, $db) {
    return mysqli_connect($server, $login, $password, $db);
};

$connection = $connect();

PS When creating questions, copy the code, do not paste screenshots.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question