refactored dbquery function