How can the connection to the database be properly established and closed in the PHP script to ensure efficient database operations?
To properly establish and close a connection to the database in a PHP script, you can use the mysqli or PDO extension. It is important to establish the connection at the beginning of the script and close it at the end to ensure efficient database operations and prevent resource leaks.
// Establishing a connection to the database using mysqli extension
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Perform database operations here
// Close connection
$conn->close();