A PHP database connection refers to the process of establishing a link between a PHP script and a database management system (DBMS) such as MySQL, PostgreSQL, or SQLite. This connection allows PHP to send queries to the database (e.g., retrieving, inserting, updating, or deleting data) and receive responses.
To create a database connection in PHP, you typically use built-in functions like mysqli_connect() (for MySQL) or PDO (PHP Data Objects) for a more database-agnostic approach. These methods require credentials such as the database host, username, password, and database name.
$host = "localhost";
$username = "root";
$password = "password";
$database = "test_db";
// Create connection
$conn = mysqli_connect($host, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
// Close connection when done
mysqli_close($conn);
$host = "localhost";
$dbname = "test_db";
$username = "root";
$password = "password";
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
For cloud-based PHP applications, Tencent Cloud offers managed database services like TencentDB for MySQL or TencentDB for PostgreSQL, which provide high availability, scalability, and security. You can easily connect your PHP application to these databases using the same methods, ensuring reliable performance for web applications.