How can SELECT queries be optimized in PHP scripts to improve performance and prevent errors like invalid result resources?

To optimize SELECT queries in PHP scripts and prevent errors like invalid result resources, it is important to properly handle the query execution and result retrieval process. One way to achieve this is by using error handling techniques such as checking for errors after executing the query and ensuring that the result resource is valid before attempting to fetch data from it.

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

// Check for errors
if (!$result) {
    die("Error executing query: " . mysqli_error($connection));
}

// Check if result resource is valid
if (mysqli_num_rows($result) > 0) {
    // Fetch data from result
    while ($row = mysqli_fetch_assoc($result)) {
        // Process data
    }
} else {
    echo "No results found.";
}

// Free the result resource
mysqli_free_result($result);