Refactor MySQL query function.