mysql: Put most of the code into a function.