I can connect to localhost using mysqli_connect, but I can’t connect to any other sql server

I am trying to connect to an sql server using mysqli_connect but I keep getting either “php_network_getaddresses: getaddrinfo failed: Name or service not known” or “No connection could be made because the target machine actively refused it” or “Error while reading greeting packet”

However, when I connect to an sql on my local host, it works fine.

Here’s my php:

// details used to connect to sql database
$servername = "localhost";
$username = "root";
$password = "123";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
   die("Connection failed: " . mysqli_connect_error());
}

If I change the login details to that of any other server, it doesn’t work. What am I doing wrong?

I tried changing the details to the server ip and login details of another sever that connects fine with ssms but when I try to connect with php, it doesn’t work and throws up an error. If I can connect with ssms, why wouldn’t I be able to connect with php?

I’ve tried using php hosted on my localhost and php hosted on 123-reg, both with similar results.