Clean and refactor MySQL check

Refactor, follow coding convention, do less MySQL queries and fix #559