How can database queries be optimized to prevent memory limit issues in PHP?

Database queries can be optimized to prevent memory limit issues in PHP by fetching data in smaller chunks rather than loading the entire dataset into memory at once. This can be achieved by using techniques like pagination or limiting the number of rows fetched per query.

// Example of fetching data in smaller chunks using pagination
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

$query = "SELECT * FROM table_name LIMIT $limit OFFSET $offset";
$result = mysqli_query($connection, $query);

while ($row = mysqli_fetch_assoc($result)) {
    // Process each row here
}