Removed closing PHP tag.
Use safe_rows_start() for the queries.

Reduces peak memory usage.
Updated formatting.
SQL formatting.
Moved initialization to the end.