What are some tips for optimizing database queries within recursive PHP functions?

When dealing with recursive PHP functions that interact with a database, it's important to optimize database queries to prevent unnecessary calls and improve performance. One way to achieve this is by passing database connections as parameters to the recursive function, rather than establishing a new connection each time the function is called. This helps reduce overhead and improve efficiency.

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Recursive function with database connection as a parameter
function recursiveFunction($pdo, $parent_id) {
    // Perform database query using the provided connection
    $stmt = $pdo->prepare("SELECT * FROM table WHERE parent_id = :parent_id");
    $stmt->execute(array(':parent_id' => $parent_id));
    
    // Process results
    while ($row = $stmt->fetch()) {
        // Recursive call with the same connection
        recursiveFunction($pdo, $row['id']);
    }
}

// Initial call to the recursive function
recursiveFunction($pdo, $parent_id);