PHP MySQL Connection Script for Health Check
This PHP script demonstrates how to connect to a MySQL database using themysqli extension.
Prerequisites
- Ensure you have PHP installed on your server.
- Ensure you have MySQL installed and a database created.
Script Breakdown
Step 1: Define Database Connection Parameters
- $hostname: The hostname of your MySQL server, typically ‘localhost’.
- $username: The username to access the MySQL database.
- $password: The password associated with the username.
- $database: The name of the database you want to connect to.
Step 2: Establish Database Connection
- $conn: This variable holds the connection object returned by
new mysqli()function.
Step 3: Check Connection
- $conn->connect_error: This property checks if there was an error connecting to the database.
- die(): If there is a connection error, this function stops the script execution and outputs the error message.
- echo ‘Connected successfully’: If the connection is successful, this message will be displayed.
Complete Script
How to Use
-
Replace the placeholder values:
your_db_usernamewith your actual database username.your_db_passwordwith your actual database password.your_db_namewith the name of your database.
-
Save the script as a
.phpfile (e.g.,db_connect.php). - Upload the script to your PHP server.
-
Access the script via a web browser (e.g.,
http://yourserver.com/db_connect.php).
If the connection is successful, you will see the message “Connected successfully.” If there is an error, the message “Connection failed: ” followed by the error details will be displayed.
