Reworking the Logic for the db loop