Goal: Help you confirm if MySQL is accessible, if the credentials are correct, and identify where the issue lies (network, firewall, service, port, SSL/TLS, permissions, or code).
Test Your Website Connection to a MySQL Database via PHP
Follow the steps below to quickly test your MySQL connection:
1. Copy and paste the PHP code below into a text editor (Notepad our Notepad++) and save it as mysqltest.php.
2. Upload the file to your hosting server inside the public_html folder using FTP.
<?php
$host = "HOST_MYSQL"; // ex: localhost or mysql.yourdomain.com
$user = "USER";
$pass = "PASSWORD";
$db = "NAME_DATABASE"; // optional
$conn = @mysqli_connect($host, $user, $pass, $db);
if (!$conn) {
die("❌ Connection error: " . mysqli_connect_error());
}
echo "✅ MySQL connection successful!<br>";
$result = mysqli_query($conn, "SELECT NOW() AS now, VERSION() AS versao");
$row = mysqli_fetch_assoc($result);
echo "Server time: " . $row['agora'] . "<br>";
echo "Version MySQL: " . $row['versao'];
mysqli_close($conn);
?>
Important: Before running the script, update the following variables:
HOST_MYSQL = Database server address. Usually this is set as localhost.
USER = The username created to access the database.
PASSWORD = The password assigned to that user.
NAME_DATABASE = The name of the database you created.
3. Ioen your browser and access the file you uploaded FTP using the URL: http://yourdomain.com/mysqltest.php
4. If the connections works, you will see a success message showing the current time and MySQL version.
5. Always remember to delete this file afterward to avoid exposing your database credentials.
Conclusion
Testing the connection with your MySQL database is an essential step to ensure that your application works properly and without unexpected errors. With this simple PHP script uploaded via FTP, you can quickly validate if your credentials, server, and port are configured correctly.
This test also helps identify whether the issue lies in the application code, server, sutup, or database permissions, saving valuable time in trobleshooting. Once the connection has been confirmed, always remove the test file to keep your environment safe and secure.
Lizzie Patrick
Writer and Programmer
-------------------------------------------------
Did you like this tip? Help our website stay online so we can create more articles like this. Contribute with any amount of donation.