Improve mysql queries and handling