Your code is vulnerable to SQL Injection
use string concatenation to build a SQL query. ALWAYS
use a parameterized query.
Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange
Query Parameterization Cheat Sheet | OWASP
Beyond that, don't use
to send data to the response. As you have discovered, the text you write will be send before the HTML generated by the view. And if you think about it, that's entirely expected - your code has no way of knowing that you want the text to be inserted at some point within your view, nor where you would want to insert it. Instead, pass the details to your view as part of the model, or within the
dictionary, and output the required values within the view.