If you have mysqli extension installed with PHP and you use it to perform database operations, after you have tried to connect to MySQL by:
$conn = new mysqli('localhost', 'db_user', 'db_pwd', 'db_name');
You can then check if the connection is successful by:
if ($conn -> connect_errno) {
// failure
} else {
// success
}
That’s because connect_errno contains the error number of the last query. If there’s no error, it’s 0 by default. If an error occurred in the last query, it’s a natural number greater than zero. There you go with the conditional check of whether the PHP database connection is successful.
However if you are using the legacy mysql extension to connect to MySQL databases:
$conn = mysql_connect('localhost', 'db_user', 'db_pwd');
It’s even simpler. The returned value of mysql_connect() function will be FALSE should the connection fail. Therefore, you can check if the connection is successful by:
if ($conn = mysql_connect('localhost', 'db_user', 'db_pwd')) {
// success
} else {
// failure
}
Related Posts
- MySQL: How to backup ALL databases as root with mysqldump at once?
- MySQL: Select and Show all MySQL Users
- You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax …
- PHP: Escape String Literals for SQL, mysqli::real_escape_string and PDO to Prevent SQL Injection Attacks
- How to Recover or Reset MySQL root Password after You Forgot and Lost It
