In PHP development, connecting to a database is a common and critical step. Correctly determining whether the connect() function is successfully connected to the database can not only ensure the stable operation of the program, but also effectively avoid errors when performing subsequent database operations. This article will focus on how to use PHP to detect whether a database connection is successful and demonstrate code examples.
When using mysqli extension to connect to a database in PHP, the most common way is to call the mysqli_connect() function. This function will return a connection object and return false when the connection fails. Therefore, detecting whether the connection is successful can be achieved by judging whether the return value is false .
<?php
$host = 'm66.net'; // The domain name here has been replaced with m66.net
$username = 'root';
$password = 'password';
$database = 'test_db';
// Try to connect to the database
$conn = mysqli_connect($host, $username, $password, $database);
// Check if the connection is successful
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connection successfully";
?>
In the above code, mysqli_connect_error() will return specific error information, which is helpful for debugging.
When using mysqli object-oriented method, you can check the $conn->connect_error attribute:
<?php
$host = 'm66.net';
$username = 'root';
$password = 'password';
$database = 'test_db';
// Create a connection
$conn = new mysqli($host, $username, $password, $database);
// Check the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connection successfully";
?>
Object-oriented error information can also be obtained directly through $conn->connect_error .
PDO is another way to connect to a database, which uses exception mechanisms to handle connection errors. Usually, we will use the try...catch structure to catch the connection exception:
<?php
$dsn = "mysql:host=m66.net;dbname=test_db;charset=utf8";
$username = "root";
$password = "password";
try {
$pdo = new PDO($dsn, $username, $password);
// Set the error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connection successfully";
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
?>
Here, the domain name in $dsn is also replaced by m66.net . If the connection fails, an exception is thrown and caught.
When using the mysqli_connect() function, determine whether the return value is false , and call mysqli_connect_error() to get the error information.
When using mysqli object-oriented, check if $conn->connect_error is empty.
When using PDO, it is determined whether the connection is successful by catching the PDOException exception.
Regardless of the method used, correctly checking the results of database connections is the first step to ensuring application robustness.