You use PHP and MySQL together seamlessly on your website. This one day, out of the blue, you get a database connection error. Although a database connection error could indicate a bigger problem, it is usually a result of one of a few scenarios:
Everything Was Fine Yesterday
You could connect yesterday and haven't changed any code in your script. Suddenly today, it's not working. This problem probably lies with your web host. Your hosting provider may have the databases offline for maintenance or because of an error. Contact your web server to see if that is the case and, if so, when they are expected to be back up.
If your database is on a different URL than the PHP file you are using to connect to it, it could be that you let your domain name expire. Sounds silly, but it happens a lot.
I Can't Connect to Localhost
Localhost doesn't always work, so you need to point directly to your database. Often it's something like mysql.yourname.com or mysql.hostingcompanyname.com. Replace "localhost" in your file with the direct address. If you need help, your web host can point you in the right direction.
My Host Name Won't Work
Double-check your username and password. Then, triple-check them. This is one area people often overlook, or they check so quickly they don't even notice their mistake. Not only do you need to check that your credentials are correct, you should also make sure you have the correct permissions required by the script. For example, a read-only user can't add data to the database; write privileges are necessary.
The Database Is Corrupt
It happens. Now we're entering the territory of a bigger problem. Of course, if you keep your database backed up regularly, you're going to be all right. If you know how to restore your database from a backup, by all means, go ahead and do it. However, if you've never done this, contact your web host for help.
Repairing a Database in phpMyAdmin
If you use phpMyAdmin with your database, you can repair it. Before you begin, make a backup of the database-just in case.
- Log in to your web server.
- Click the phpMyAdmin icon
- Choose the affected database. If you only have one database, it should be chosen it by default.
- In the main panel, you should see a list of the database tables. Click Check All.
- Choose Repair Table from the drop-down menu.