What best practices should be followed when constructing SQL queries in PHP to avoid errors like "supplied argument is not a valid MySQL result resource"?

When constructing SQL queries in PHP, it is important to ensure that the query is executed successfully and returns a valid MySQL result resource. To avoid errors like "supplied argument is not a valid MySQL result resource," you should check if the query executed successfully before attempting to fetch results.

// Example of constructing SQL query in PHP to avoid errors
$query = "SELECT * FROM users";
$result = mysqli_query($connection, $query);

if ($result) {
    // Query executed successfully, fetch results
    while ($row = mysqli_fetch_assoc($result)) {
        // Process results here
    }
} else {
    // Query failed, handle error
    echo "Error: " . mysqli_error($connection);
}