fix mysql query
various bug fixes