fixed a few bugs in database query