More changes and fixes from PDO conversion. Also refactoring some code where redundant