Skip to main content

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: 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

  1. 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.
  2. Save the script as a .php file (e.g., db_connect.php).
  3. Upload the script to your PHP server.
  4. 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.