Fix for issue #83: code uses db result before it exists

See comment thread attached to #83 for details and style discussion. This is how I would do it, style-wise, but others may disagree.