0

There are some nice php database connection tests around, but they all seem to require a username & password. How would one confirm (using php and presumably mysqli) that a database server is up and would accept connections should one be attempted with a correct username & password, but report some details on the failure if the server was down or timed out or what not.

2
  • 2
    Look for a difference in the error message. If the server is offline you'll get a different error message when trying to connect than you will if it's there but it doesn't recognise the credentials. Or you could just try and telnet to the port. Commented Dec 12, 2020 at 17:23
  • 1
    I have to say this is a rather strange requirement. Credentials are set up by the system administrator so if your access is denied then it means the server is not reachable from your POV. Commented Dec 12, 2020 at 17:30

1 Answer 1

3

I would use the code 1045 to see if you can connect. This error code indicates that the credentials are incorrect. If the server responds with that code then it means it is reachable.

<?php

$reachable = false;

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
    $mysqli = new mysqli('localhost', 'some invalid user', 'wrong password');
} catch (mysqli_sql_exception $e) {
    if (1045 === $e->getCode()) {
        $reachable = true;
    }
}

var_dump($reachable);
?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.