0

I am building a project with installation (suck as WordPress) and the user provides database information (server, username, password and database). Now, I have to check if it can connect to the provided database. I tried this code, but it seems that it does not work (I am using Mysqli btw):

public function checkDataBaseConnection($server, $user, $pass, $db)
{
    $conn = @mysqli_connect($server, $user, $pass, $db);
    if(mysqli_connect_error())
    {
        return FALSE;
    }
    else
    {
        mysqli_close($conn);
        return TRUE;
    }
}

What other way can I use to check if the server can connect to the database?

3 Answers 3

1

One thing: Remove the @, that suppresses some php warnings.

Second thing: Try this:

public function checkDataBaseConnection($server, $user, $pass, $db)
{
    $conn = @mysqli_connect($server, $user, $pass, $db);
    if(!$conn)
    {
        return FALSE;
    }
    else
    {
        //mysqli_close($conn); why would you close the connection?
        return $conn;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Have you tried something like this?

if (checkDataBaseConnection($server, $user, $pass, $db))
   echo "Success!";
else
   echo "Fail.";

By the way you just can do this way

mysqli_connect($server, $user, $pass) or die('Connection failed');

Comments

0

Well, if you look at the PHP page for mysqli_connect you can see this example:

<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

/*
 * This is the "official" OO way to do it,
 * BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
 */
if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '
            . $mysqli->connect_error);
}

/*
 * Use this instead of $connect_error if you need to ensure
 * compatibility with PHP versions prior to 5.2.9 and 5.3.0.
 */
if (mysqli_connect_error()) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

echo 'Success... ' . $mysqli->host_info . "\n";

$mysqli->close();
?>

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.