My database connection stopped working. I was using the following connection code and hadn't made any changes to anything on the php page or the connection page with this code:
<?php
@ $db = new mysqli('localhost', 'user', 'pass', 'db');
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
?>
I changed to this code
<?php
function db_connect() {
$result = new mysqli('localhost', 'user', 'pass', 'db');
if (!$result) {
throw new Exception('Could not connect to database. Please try again later.');
} else {
return $result;
}
}
?>
and the connection works.
Why would this be? I don't understand what the difference between the two is and why the first code would stop connecting to the database.