user52587 user52587 - 1 month ago 4x
PHP Question

Included file in PHP can't access database

I have recently run across a really weird problem. I have a PHP file named "functions.php" and a file called "login.php" that includes function.php and uses the functions inside to connect to my database. That should work right? it acts normally until I try to access my database where I get:

mysqli::mysqli(): (28000/1045): Access denied for user 'root'@'localhost' (using password: NO)
I have searched the web pretty well and haven't found anything remotely similar and it does it on two different hosts too so I am utterly stumped.


function connect(){
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
return $conn;


Your variables do not exist within the scope of the function. Either pass it in

function connect($username,$password,$servername){

Or place the variables inside of your function if you do not need them anywhere else.

You can read more about variable scopes here.