Introduction:
Connecting to a database is a common task in PHP, especially when working with dynamic web applications. PHP provides the mysqli
or PDO
extension to establish and manage a database connection.
Example:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create a connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Explanation:
$servername
,$username
,$password
, and$dbname
hold the connection details for the MySQL database.new mysqli()
creates a connection to the MySQL server.connect_error
checks if there was an error in connecting. If there is, thedie()
function stops execution and prints the error.- If the connection is successful, the script outputs “Connected successfully”.