refactor db.php (please check for bugs...)