Reputation: 1830
I'm building a small self-hosted app which requires database usage. I'd like to validate that the user inputted database credentials are valid, before they're actually saved. What could I do to check whether or not a connection is valid, would it be as simple as?
$conn = mysql_connect($db_name, $db_user, $db_pass); mysql_select_db($db_name);
if($conn) {
mysql_close($conn);
// Do stuff if connection is valid
} else {
mysql_close($conn);
// Do stuff if connection is invalid
}
Would I even need to close the connection if it's invalid? (Within the else{}
statement. I took a look at mysql_ping()
but it doesn't really seem to be what I need.
Upvotes: 2
Views: 2090
Reputation: 561
also frequently used is 'die' which allows you to print a message before stopping execution of the script:
$conn = mysql_connect($db_name, $db_user, $db_pass) or die('the error message');
or for debugging purposes the following is frequently used:
$conn = mysql_connect($db_name, $db_user, $db_pass) or die(mysql_error());
which will print the mysql error such as a warning about wrong credentials
Upvotes: 0
Reputation: 1701
If the credentials are invalid, no need to close the connection as it won't be open in the first place.
Upvotes: 4