What are the best practices for optimizing queries in PHP when dealing with large datasets?

When dealing with large datasets in PHP, it is important to optimize queries to improve performance. One way to do this is by using indexes on columns frequently used in WHERE clauses. Additionally, limiting the number of columns selected and using pagination can help reduce the amount of data processed.

// Example of optimizing a query using indexes
$query = "SELECT * FROM users WHERE username = 'john_doe'";
// Add an index on the username column in the users table
$index_query = "CREATE INDEX idx_username ON users(username)";
// Execute the index query before running the main query
// $result = mysqli_query($connection, $index_query);
// $result = mysqli_query($connection, $query);