Sometimes, to make your code testable, you have to refactor it. The subroutine you showed is a good candidate:
Testable subroutine should only do one thing. The one you showed does three: connects to a database (read about "mocking"), constructs a SQL string, htmlizes the result.