What steps should be taken to ensure a successful connection to the database when executing a query in PHP?

To ensure a successful connection to the database when executing a query in PHP, you need to establish a connection to the database using appropriate credentials, select the database you want to work with, and then execute your query using the established connection.

// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Execute your query
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

// Process the result
if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
    }
} else {
    echo "0 results";
}

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