0

I'm trying to my project's MySQL database with mysqli_connect() but I'm getting an error:

Database connection failed: php_network_getaddresses: getaddrinfo failed: Name or service not known (2002)

I have another project running fine on the same server.

How can I fix this?

<?php

define('DB_HOST', 'localhost');
define('DB_USER', 'mydb_admin');
define('DB_PASS', 'SomePass');
define('DB_NAME', 'my_db');

function db_connect()
{
  $db =  mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
  confirm_db_connect();
  return $db;
}

function confirm_db_connect()
{
  if (mysqli_connect_errno()) {
    $msg = 'Database connection failed: ';
    $msg .= mysqli_connect_error();
    $msg .= ' (' . mysqli_connect_errno() . ')';
    exit($msg);
  }
}

function db_disconnect()
{
  if (isset($db)) {
    mysqli_close($db);
  }
}

$db = db_connect();
Dharman
  • 30,962
  • 25
  • 85
  • 135
jixodoj
  • 179
  • 2
  • 11

1 Answers1

-1
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;}
echo "Success: A proper connection to MySQL was made!" .PHP_EOL;
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;

mysqli_close($link);

Test the above code, it will show you the errors, your own code did not have a problem, you should see if the information you entered is correct or not

  • You need to stop manually checking for errors. Please read: [Should we ever check for mysqli_connect() errors manually?](https://stackoverflow.com/q/58808332/1839439) and [Should I manually check for errors when calling “mysqli_stmt_prepare”?](https://stackoverflow.com/q/62216426/1839439) – Dharman Oct 25 '20 at 13:48