What best practices should be followed when handling MySQL connections and queries in PHP to prevent errors like "supplied argument is not a valid MySQL-Link resource"?

When handling MySQL connections and queries in PHP, it is important to ensure that the connection resource is valid before executing queries. This error typically occurs when a query is attempted on a connection that is not properly established or has been closed. To prevent this error, always check if the connection is valid before executing queries.

// Establish a MySQL connection
$connection = mysqli_connect("localhost", "username", "password", "database");

// Check if the connection is valid before executing queries
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Example query
$sql = "SELECT * FROM table";
$result = mysqli_query($connection, $sql);

// Check if the query was successful
if (!$result) {
    die("Query failed: " . mysqli_error($connection));
}

// Process the query results here

// Close the connection
mysqli_close($connection);