No wonder this gives you problems.
You are building a connection and you proceed to fire queries until the user presses stop.
That's not the way to do it, because this will keep a connection open for each and every user that visits your page.
Luckily you put a sleep(1) in. You must have had some pretty bad performance at first, with this script firing as many queries as it could per second.
You need to re-think the strategy.
Instead of constantly querying the database and tying up all your resources,
make the your page auto-refreshing through some HTML or Javascript code.
Once every 5-10 seconds is more than enough. People don't type whole sentences in 5 seconds... well... the experienced chatter might, but it takes longer than 5 seconds to load the page, so 10-20 seconds is more than enough.
That way, each pageview will give only one query to the database, instead of the current hunderds of queries. (if a user doesn't press stop in your page, it will keep querying the database once every second)
And after 10 or so seconds the page auto-refreshes. If the chat had new entries they will be shown.