'MySQL - Connection failed: No route to host

Confused why getting this issue while trying to connect to my DB.

Connection failed: No route to host

<?php
$servername = "HOST";
$username = "USERNAME";
$password = "PASSWORD";
$database = "DBNAME";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

// echo $_SERVER['SERVER_NAME'];
?>

Can anyone provide a solution to connect?



Solution 1:[1]

Your $servername should be localhost not HOST

Change $servername = "HOST"; to $servername = "localhost";

If localhost doesn't work, contact your web host to ask what their particular host variable is the correct IP address to use. localhostor 127.0.0.1 are common variables.

Also, as Adrenaxus pointed out, be sure to provide the actual username, password and database name in your variables.

Solution 2:[2]

1) Check the mysql service that it is running.

2) Check the firewall that the mysql port is open.

3) If the database is located on a remote hosting check that the connection to your database can be opened.

4) If there is a router between the database, check the port forwarding.

Solution 3:[3]

Declare $PORT = '<yoursqlport>' Then, replace $conn

$conn = new mysqli($servername, $username, $password, $database, $PORT);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nimantha
Solution 2 Mubinjon Muinov
Solution 3 moepheh