PHP MySQL Connection Script for Health Check
This PHP script demonstrates how to connect to a MySQL database using the mysqli
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 = 'localhost';
$username = 'your_db_username';
$password = 'your_db_password';
$database = 'your_db_name';
- $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 = new mysqli($hostname, $username, $password, $database);
- $conn: This variable holds the connection object returned by
new mysqli()
function.
Step 3: Check Connection
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}
echo 'Connected successfully';
- $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
<?php
$hostname = 'localhost';
$username = 'your_db_username';
$password = 'your_db_password';
$database = 'your_db_name';
$conn = new mysqli($hostname, $username, $password, $database);
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}
echo 'Connected successfully';
?>
How to Use
-
Replace the placeholder values:
your_db_username
with your actual database username.your_db_password
with your actual database password.your_db_name
with the name of your database.
-
Save the script as a
.php
file (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.