How can PHP queries be optimized to improve performance and reduce the number of database connections?
PHP queries can be optimized by reducing the number of database connections made. One way to achieve this is by reusing the same database connection throughout the script instead of opening a new connection for each query. By using a persistent database connection, the overhead of establishing a new connection for each query can be eliminated, improving performance.
// Create a function to establish a persistent database connection
function getDBConnection() {
static $conn;
if(!$conn) {
$conn = mysqli_connect('localhost', 'username', 'password', 'database');
}
return $conn;
}
// Example of using the persistent connection in a query
$conn = getDBConnection();
$query = "SELECT * FROM users";
$result = mysqli_query($conn, $query);
// Use the result set as needed