Escape values in SQL queries

This adds `$db->escape_sql()` to potentially unsafe database queries.

There seem to be quite a few places remaining where this would be appropriate. I'm happy to send in a few more PRs for it.