Posted on Leave a comment

How to Connect PHP to MySQL Database in Hostinger

blue elephant figurine on macbook pro

Connecting PHP to a MySQL database is a fundamental step in building dynamic web applications. In this guide, we will walk you through the process of connecting PHP to a MySQL database in Hostinger, a popular web hosting provider.

Step 1: Create a MySQL Database in Hostinger

The first step is to create a MySQL database in your Hostinger account. Follow these steps:

  1. Login to your Hostinger account and navigate to the “MySQL Databases” section.
  2. Click on the “Create New Database” button.
  3. Enter a name for your database and click on the “Create” button.

Step 2: Retrieve Database Connection Details

After creating the database, you will need to retrieve the connection details. Here’s how:

  1. Go back to the “MySQL Databases” section in your Hostinger account.
  2. Find the database you just created and click on the “Manage” button.
  3. Scroll down to the “Database Details” section and take note of the following information:
    • Database Name
    • Database Username
    • Database Password
    • Database Host

Step 3: Connect PHP to MySQL Database

Now that you have the necessary database connection details, you can proceed to connect PHP to your MySQL database. Follow these steps:

  1. Create a new PHP file on your local machine or in your Hostinger hosting account.
  2. Open the PHP file and add the following code to establish a connection to the MySQL database:
<?php
$servername = "your_database_host";
$username = "your_database_username";
$password = "your_database_password";
$database = "your_database_name";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

Make sure to replace the placeholders with your actual database connection details.

Step 4: Test the Connection

To test if the PHP script successfully connects to the MySQL database, you can run the PHP file in a web browser or through the command line. If the connection is successful, you will see the “Connected successfully” message.

Now you have successfully connected PHP to your MySQL database in Hostinger. You can use this connection to perform various database operations, such as retrieving data, inserting records, updating data, and deleting records.

Remember to always close the database connection after you have finished working with the database. You can use the following code to close the connection:

$conn->close();

Connecting PHP to a MySQL database in Hostinger is a crucial step in developing dynamic web applications. By following the steps outlined in this guide, you can establish a secure and reliable connection to your MySQL database and leverage its power to create dynamic and interactive websites.