How can database queries impact the speed of PHP websites?

Database queries can impact the speed of PHP websites by causing delays if they are not optimized. To improve performance, queries should be written efficiently, indexes should be used where appropriate, and unnecessary queries should be avoided. Caching query results can also help reduce the load on the database and speed up website performance.

// Example of caching query results in PHP
$key = 'cached_query_results';
$cache = new Memcached();
$cache->addServer('localhost', 11211);

if ($data = $cache->get($key)) {
    // Use cached data
    echo "Using cached data: " . $data;
} else {
    // Perform the database query
    $result = $db->query("SELECT * FROM table");
    
    // Store the query results in the cache
    $cache->set($key, $result);
    
    // Use the query results
    while ($row = $result->fetch_assoc()) {
        // Process the data
        echo $row['column'];
    }
}