简体   繁体   中英

Why isn't my PHP able to connect to MySQL?

I am trying to connect to my MySQL database using the following PHP code

<?php

require "credentials.php";

$conn = mysqli_connect($hostname, $username, $password, $databaseName);

if(mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

?>

And I am getting the following output:

Failed to connect to MySQL: Connection refused

What could be the reasons that this is happening, and how can I fix it?

Thanks in advance.

from your code it seems that you are using undefined variables to connect to database. if you load them from external file, than use something like this in that file:

define("DBPASSWORD", "database_pass");
define("DBUSERNAME", "databaseusername");
define("DBNAME", "database");
define("DBHOST", "database_host");

and than use in file you shown us:

$conn = mysqli_connect(DBHOST, DBUSERNAME, DBPASSWORD, DBNAME);

OR another way, the way I can't recomend is using globals.

WARNING: I discourage using globals, when not needed.

Your credentials.php should look like that:

global $databaseName;
global $password;
global $username;
global $username;
$databaseName= "db_name";
$password= "db_password";
$username= "db_username";
$hostname= "db_host";

and than in other places, first you need to call the globals before usage.

require "credentials.php";

global $databaseName;
global $password;
global $username;
global $username;

$conn = mysqli_connect($hostname, $username, $password, $databaseName);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM