Fixed fatal db errors due to incorrect logic

Errors not occuring on MySQL, though the logic is certainly wrong there as well

Change-Id: I006c3059e087be5e5c640dd56d3f93917c69967d