I had a quick look at your code and I see the issue.
In your code, you have defined the database hostname like this:
$servername = "sql313.infinityfree.com ";
There is another tab character at the end of the hostname. And yes, that matters. Extra characters, even if it’s just whitespace, will change the value and make it invalid.
If you remove the extra whitespace characters, your code should just work.