@anlai why are you flushing inside of the foreach?  Wouldn't you want to flush your changes after going through all of your courses was finished?