Home >Database >Mysql Tutorial >Why am I getting a 'Failed to connect to MySQL server' error in PHP?
Connecting to a MySQL Database in PHP Using the mysqli Extension
When connecting to a remote MySQL database using the mysqli extension in PHP, you may encounter an error message indicating a failed connection. This is often due to an incorrect or missing server name.
In your code, you have omitted the server name from the mysqli_connect function call:
$con = mysqli_connect("", "username", "password", "databasename");
This can lead to connection failures because the MySQL server address is not specified. To resolve this issue, you can provide the server name as the first parameter of the mysqli_connect function.
Using PHP MySQLi Procedural
Alternatively, you can use the MySQLi procedural style to connect to the database:
$servername = "localhost"; $username = "username"; $password = "password"; // Create connection $con = mysqli_connect($servername, $username, $password); // Check connection if (!$con) { die("Connection failed: " . mysqli_connect_error()); }
Specifying Server Name for Localhost
If you are connecting to a local MySQL database, you can use the localhost string as the server name:
$con = mysqli_connect("localhost","username" ,"password","databasename");
Default MySQL Credentials
You may also need to adjust the username and password parameters in the mysqli_connect function to match the credentials of your MySQL database. By default, the root user with an empty password is used for local connections:
$servername = "localhost"; $username = "root"; $password = "";
The above is the detailed content of Why am I getting a 'Failed to connect to MySQL server' error in PHP?. For more information, please follow other related articles on the PHP Chinese website!