Updated db.php, small fixes and some refactoring.