Best time to open and close a database

Below is a hypothetical example of the creation of a ‘Documents’ array:

function get_documents(){

  $categories=get_categories();
  $documents=add_documents($categories);

}

function get_categories(){
 //Selects categories from categories table and creates an array
}

function add_documents($categories){
  //loops through $categories and selects documents that belong to each
  //creating a multi-dimensional array()
}

I’ve been in the practice of opening and closing the database within both get_categories() and add_documents(). This seems redundant but I’ve found when I open and close the db in the higher function the results are inconsistent. Sometimes it works and sometimes it doesn’t.

Could someone provide clarification on this?

Thank you.

E

Are you using OOP? If you are consider creating a database object at the start of execution which would get passed round to whatever functions need it, you would then only ever have one connection to the database open (unless you open another connection elsewhere). Unless you use permanent connections php will automatically close all database connections at the end of the execution of a script