How can one effectively manage database connections and queries in PHP to avoid errors like "Error connecting to mySQL database"?

To effectively manage database connections and queries in PHP to avoid errors like "Error connecting to mySQL database," you can use try-catch blocks to handle exceptions that may occur during the connection process. Additionally, you can use functions like mysqli_connect_errno() and mysqli_connect_error() to check for errors and display appropriate error messages.

<?php

$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);
}

echo "Connected successfully";

// Perform database operations here

// Close connection
$conn->close();

?>