Current Location: Home> Latest Articles> How to Fix PHP Unable to Connect to MySQLi Database Issue

How to Fix PHP Unable to Connect to MySQLi Database Issue

gitbox 2025-07-02

Check Connection Information

To resolve the issue of PHP not being able to connect to MySQLi, first ensure that the connection information is correct. Make sure the following details are accurate:

  • Host name
  • Username
  • Password
  • Database name

Ensure that this information matches your MySQL database configuration.

Check if MySQL Service is Running Properly

If the connection information is correct, you need to make sure that the MySQL service is running properly. You can check this by following these steps:

Check MySQL Service Status

You can use the following command to check the status of the MySQL service:

<span class="fun">systemctl status mysql</span>

Make sure the output status is "active".

Start MySQL Service (if it is not running)

If MySQL service is not running, you can start it with the following command:

<span class="fun">sudo systemctl start mysql</span>

Check if PHP Extension is Loaded

The connection between PHP and MySQL depends on the MySQLi extension. After confirming that MySQL service is running, you also need to ensure that the MySQLi extension is properly loaded.

Check if MySQLi Extension is Enabled

Open the php.ini file and look for the following line:

<span class="fun">extension=mysqli</span>

If the semicolon (;) before this line is not commented out, remove the semicolon and save the file. Then restart the Apache server.

Check if MySQLi Extension is Correctly Loaded

You can find information about the MySQLi extension in the output of the phpinfo() function. Create a simple PHP file (e.g., info.php) with the following content:

<?php
phpinfo();
?>

After accessing this file, search for "mysqli" in your browser to check if the relevant information is displayed.

Check the Connection Code

Finally, make sure that your connection code is correct. Here’s a basic example of the connection code:

<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

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

// Check if connection is successful
if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}

echo "Connection successful!";
?>

Ensure that your connection information matches the example code above.

Conclusion

If your PHP cannot connect to MySQLi, first check if the connection information is correct. Then make sure the MySQL service is running and check if the MySQLi extension is loaded. Finally, verify that the connection code is correct. By following these steps, you should be able to resolve the issue of PHP not being able to connect to MySQLi.