Fixed a few bugs.

The logic was no longer working after switch to mysqli. Changed the
code.