What steps should be taken to ensure proper database connection and query execution in PHP scripts?

To ensure proper database connection and query execution in PHP scripts, it is important to establish a secure and reliable connection to the database using appropriate credentials, handle errors effectively, and sanitize input to prevent SQL injection attacks.

<?php
// Establishing a database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";

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

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

// Executing a query
$sql = "SELECT * FROM users";
$result = $conn->query($sql);

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";
}

$conn->close();
?>