1

I have a form with fields to connect to a database. This includes hostname, database, username and password. I am using an AJAX call to connect to the database. Some error handling needs to be taken care of, one of them is failing to connect to the database.

The exception is caught in a try-catch statement, I update the $result variable with the error message. This is then returned to the AJAX call.

Here is a simplified version of the code:

AJAX Call:

$.ajax({
    url: _url + 'dbv.php',
    type: 'POST',
    data: {
        db_host: $('input[name="db_host"]').val(),
        db_name: $('input[name="db_name"]').val(),
        db_username: $('input[name="db_username"]').val(),
        db_password: $('input[name="db_password"]').val(),
        save_path: $('input[name="save_path"]').val()
    },
    dataType: 'json',
    success: function(data) {
        if (data.error) {
            console.log('success (error): ' + JSON.stringify(data));
        }
        else {
            console.log('success: ' + JSON.stringify(data));
        }
    },
    error: function(data) {
        console.log('error: ' + JSON.stringify(data));
    }
});

PHP:

try {

    if ($_POST['db_host'] && $_POST['db_username'] && $_POST['db_password'] && $_POST['db_name'] && $_POST['save_path']):

        $host = $_POST['db_host'];
        $user = $_POST['db_username'];
        $password = $_POST['db_password'];
        $database = $_POST['db_name'];
        $path = $_POST['save_path'];

    else:

        throw new Exception('Empty Fields', '1');

    endif;

    if (!$result->error):

        $conn = new mysqli($host, $user, $password, $database);

        // ...

        mysqli_close($conn);

    endif;
}
catch (Exception $e) {
    $result->error = true;
    $result->message = 'Error: ' . $e->getMessage();
}

$result->message = (!$result->error) ? 'Successful' : $result->message;
echo json_encode($result);

The first exception in the code, Empty Fields, is caught and returned to the success function. The issue I'm having is that the error AJAX state is fired not when the database connection is incorrect. The returned data includes both PHP's default error message and the $result variable. Shouldn't this be just the $result variable, same as the Empty Fields Exception?

Screenshots of what's happening:

Exception firedException is caught

Error responseText including both PHP's error and $result variable:

"responseText":

PHP's error:

"Warning: mysqli::mysqli(): php_network_getaddresses: getaddrinfo failed: No such host is known. in ____\dbv.php on line 35

$result variable:

{\"error\":true,\"message\":\"Error: php_network_getaddresses: getaddrinfo failed: No such host is known. \"}"

I've been searching quite a bit and it looks like the logic is fine - maybe there's something I'm completely missing.

Two examples similar to what I'm trying to do: https://stackoverflow.com/a/20938633/1275525, https://stackoverflow.com/a/12693587/1275525

j.grima
  • 1,831
  • 3
  • 23
  • 45
  • 1
    Possible duplicate of [Catching mysql connection error](https://stackoverflow.com/questions/11826659/catching-mysql-connection-error) – Masivuye Cokile May 24 '17 at 12:46

3 Answers3

1

I see some solutions:

  1. [GOOD] Disable connect warnings and throw custom exception, to example https://stackoverflow.com/a/14049169/1559720
  2. [BAD] Bufferize output using ob_start

For first point, example:

@$mysql = new mysqli($host, $user, $password, $database);
if ($mysql->connect_errno) {
   throw new \Exception($mysql->connect_error, $mysql->connect_errno);
}
maximkou
  • 5,252
  • 1
  • 20
  • 41
-1

host name must be: localhost. I don't think getaddrinfo it's your host. What is getaddrinfo?

NIRAV PAREKH
  • 137
  • 1
  • 2
  • 11
  • That is part of the warning. The issue is not that the host name must be `localhost`. I am testing out incorrect details on purpose to handle errors. – j.grima May 24 '17 at 12:43
-2

When you catch an error you do

catch (Exception $e) {
    $result->error = true;

this means that the result that gets returned contains the info 'my error property is true' so that's why your javascript then thinks that there is an error. To reverse this behaviour you can simply omit that last line.

However, why would you want this? It seems logical for your javascript to do something different when there is an error. Like notifying the user for example.

This bit also seems a bit strange to me:

success: function(data) {
    if (data.error) {
        console.log('success (error): ' + JSON.stringify(data));
    }
    else {
        console.log('success: ' + JSON.stringify(data));
    }

As there's already a different function for success and error why would you then check for errors in the success function? This function should never even be triggered when there's an error.

Jos Vlaar
  • 11
  • 1
  • 4
  • `$result` is an array I am handling, it has nothing to do with JavaScript. An `error` function is fired when an actual error occurs. Furthermore, having `success` fired does not necessarily mean that no errors occurred. Case in point, changing the empty fields error (first if-else statement) to an exception, the `success` function is fired not `error`. You should always check for errors in `success`. – j.grima May 24 '17 at 13:07