DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
VGSources
Blog

How to Fix “Can’t Connect to MySQL” Errors in PHP

A practical guide to PHP MySQL connection failures: decode errors 2002 and 2005, test the exact endpoint with the MySQL client, fix socket and TCP settings, verify grants and drivers, and keep production diagnostics safe.
WorldPHP Length12 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A PHP–MySQL connection failure is usually one of five problems: PHP is trying the wrong Unix socket, the wrong TCP host or port, a hostname that cannot be resolved, credentials or host permissions that do not match, or a missing PHP MySQL driver. Capture the complete error, test the identical connection outside PHP with the MySQL client, then verify the entire connection tuple—host, port, socket, database, user, password and driver.

The fastest fixes are often explicit rather than clever: use 127.0.0.1 and the server’s listening port for TCP, or specify the server’s actual socket path when using a Unix socket. Keep detailed diagnostics in server logs, not in the response shown to visitors.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Classify the failure before changing code

Read the complete error message, including its numeric code and the endpoint PHP attempted. The wording usually identifies the layer that failed:

  • Socket or local endpoint: “Can’t connect to local MySQL server through socket” and error 2002 indicate that the client could not reach the local Unix-domain socket it selected.
  • Unknown host: error 2005 means the hostname could not be resolved or is not a valid MySQL endpoint from that machine.
  • TCP or port: a refused or timed-out connection generally means the server is not listening on that address and port, a firewall or network policy is blocking it, or the PHP process is using the wrong port.
  • Authentication or authorization: an “access denied” response means MySQL was reached but rejected the username, password, account host, or requested database.
  • Missing driver: messages such as “could not find driver” occur before MySQL is contacted; the PHP runtime lacks the PDO MySQL or mysqli extension required by your code.

Do not replace credentials or reinstall MySQL until the error category is clear. A socket error will not be repaired by changing a password, and a missing driver cannot be solved by opening port 3306.

Capture a safe, complete diagnostic

During troubleshooting, preserve the exact exception or connection error in a private log. Record the numeric code, host text, port, socket path, database name and PHP API in use. The endpoint in the message tells you whether to investigate a socket, DNS, or TCP path.

For mysqli, inspect the connection error through the API rather than guessing:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<?php
mysqli_report(MYSQLI_REPORT_OFF);
$mysqli = mysqli_connect($host, $user, $password, $database, $port, $socket);
if ($mysqli === false) {
    error_log('MySQL connection failed (' . mysqli_connect_errno() . '): ' . mysqli_connect_error());
    http_response_code(500);
    exit('Database connection unavailable.');
}

Object-oriented mysqli exposes the same information through $mysqli->connect_errno and $mysqli->connect_error. If your application enables strict reporting, a connection failure may be thrown as a mysqli_sql_exception instead; catch and log it at the application boundary.

PDO reports connection failures by throwing PDOException when exception mode is enabled. Log the message on the server and show visitors a generic response:

<?php
try {
    $pdo = new PDO($dsn, $user, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    ]);
} catch (PDOException $e) {
    error_log('Database connection failed: ' . $e->getMessage());
    http_response_code(500);
    exit('Database connection unavailable.');
}

Never print a password, a complete DSN containing secrets, or an internal socket path to a visitor. Those details can expose credentials and filesystem information.

Confirm MySQL independently of PHP

First establish whether the server is running and where it is listening. Check the service using the operating system’s normal service manager or your hosting control panel. The exact service command varies by distribution and hosting provider; the important result is that mysqld is running and configured to listen on the endpoint PHP will use.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Then run the MySQL command-line client with the same values used by PHP. This separates server, network and account problems from PHP configuration problems.

mysql -h 127.0.0.1 -P 3306 -u your_user -p your_database

The client prompts for the password. Do not put the password directly in the command, because it can be exposed in shell history or process listings. For a Unix socket, test the socket explicitly:

mysql --socket=/path/to/mysql.sock -u your_user -p your_database

For a remote server, substitute the actual DNS name or IP address and port. Use exactly the same host, port, username and database as the PHP request. If this command fails with the same error, fix MySQL’s listener, networking or account policy before changing PHP. If it succeeds while PHP fails, compare the PHP runtime, configuration and connection tuple.

Understand localhost versus 127.0.0.1

In PHP’s mysqli API, localhost has a special meaning: it selects a Unix-domain socket rather than TCP/IP. 127.0.0.1 selects TCP/IP. They can point to the same machine but are different transports with different configuration and failure modes.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Host value Transport selected by mysqli What must match Typical failure
localhost Unix-domain socket PHP’s socket path and the server’s socket file Error 2002 or “can’t connect … through socket”
127.0.0.1 TCP/IP loopback Listening address and port, commonly 3306 Connection refused or timeout when TCP is unavailable
A DNS name or IP address TCP/IP DNS resolution, network route, firewall and port Error 2005 for an unknown host, or a network refusal/timeout

If localhost fails but 127.0.0.1 works, the MySQL server and credentials are probably usable; PHP is likely selecting a socket that does not exist or is not the server’s actual socket. Use explicit TCP with the correct port, or correct the socket path instead. If TCP is disabled or a policy permits only local sockets, the reverse can occur: use the valid socket rather than forcing an IP address.

Use explicit TCP with mysqli

<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('127.0.0.1', $user, $password, $database, 3306);
$mysqli->set_charset('utf8mb4');

Port 3306 is the conventional mysqli and MySQL client default when no port is supplied, not a guarantee that your server uses it. Read the server configuration or hosting panel and pass the configured port explicitly.

Use the correct socket

If your application must use a Unix socket, find the path configured by the running MySQL server and pass it to mysqli. PHP’s mysqli constructor accepts host, user, password, database, port and socket; the socket argument is used when the connection is local.

<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', $user, $password, $database, 0, '/actual/path/mysql.sock');

The path in an error such as /tmp/mysql.sock may be a PHP or client default rather than the file used by the server. A different socket file is a common reason for error 2002. Compare the path character-for-character, including directories and filename.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Verify the complete connection tuple

Every successful connection requires all of these values to be correct at the same time:

  • Host: localhost, 127.0.0.1, a DNS name or an IP address.
  • Port: the TCP listener, often 3306 but not necessarily.
  • Socket: the Unix socket file when using a local socket.
  • Database: an existing schema name that the account can use.
  • Username: the exact MySQL account name.
  • Password: the current password for that account.
  • Driver and API: mysqli or PDO MySQL loaded in the PHP runtime serving the request.

Compare the values in PHP with the values that succeeded in the command-line test. A typo in the database name can appear after the server accepts the account, while an incorrect host can prevent authentication from being attempted at all.

Fix authentication and host-permission errors

A reachable server can still reject a login. MySQL accounts are identified by both username and host, so an account such as 'app'@'localhost' is not automatically the same as 'app'@'127.0.0.1' or 'app'@'web.example'. Changing from a Unix socket to TCP can therefore select a different account row even when the username text is unchanged.

Check the following with the administrator who manages the database:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • The username and password are current and belong to the intended server instance.
  • The account’s allowed host matches the source host MySQL sees.
  • The account has permission to connect and use the requested database.
  • The database name is spelled exactly as created on that server.
  • Host-name resolution settings are not causing MySQL to interpret the client host differently.

Do not “fix” access denied errors by granting broad privileges or allowing every host without understanding the security impact. Create or adjust the narrowly scoped account required by the application, and test the resulting host and transport with the command-line client.

Check DNS and remote TCP connectivity

Error 2005 identifies an unknown MySQL host. Confirm that the name is spelled correctly and resolves from the machine running PHP, not merely from your workstation. A hostname that works in a local shell may fail in a container, virtual machine or hosting environment with different DNS settings.

For a remote connection, verify the route and listener as a sequence:

  1. Resolve the database hostname from the PHP server.
  2. Confirm that MySQL is listening on the intended address and port, rather than only on a local loopback address.
  3. Check firewalls, security groups and hosting-network rules for that source and destination port.
  4. Run the MySQL client from the same machine or runtime as PHP using the exact host and port.
  5. Only after transport succeeds, investigate credentials and database grants.

A TCP timeout usually indicates filtering or an unreachable route; an immediate refusal usually indicates that no service is listening at the selected address and port. These symptoms are distinct from an authentication rejection, which proves that MySQL was reached.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Check that PHP has the required driver

PDO and mysqli are separate PHP interfaces. PDO needs the PDO MySQL driver; mysqli needs the mysqli extension. The PHP binary used in a terminal can load a different configuration from the PHP runtime serving a web request, so check the web runtime rather than relying only on a command-line module list.

If PHP says it cannot find a driver, install or enable the appropriate MySQL extension for the PHP version that serves the request, then restart that runtime. Package names and restart commands differ by operating system, PHP handler and hosting provider; verify the loaded PHP configuration instead of copying a distribution-specific command blindly.

For PDO, a DSN identifies the driver and endpoint. This example makes TCP and the port explicit:

<?php
$dsn = 'mysql:host=127.0.0.1;port=3306;dbname=' . $database . ';charset=utf8mb4';
try {
    $pdo = new PDO($dsn, $user, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    ]);
} catch (PDOException $e) {
    error_log('Database connection failed: ' . $e->getMessage());
    http_response_code(500);
    exit('Database connection unavailable.');
}

To use a Unix socket with PDO, specify the socket in the DSN in the form supported by your PHP version and deployment, and ensure the web-process user can access that socket. Keep the endpoint consistent with the command-line test; mixing a socket test with a TCP DSN can send you down the wrong diagnostic path.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose mysqli or PDO without mixing assumptions

Decision point mysqli PDO MySQL
Connection syntax Constructor or mysqli_connect() accepts host, user, password, database, port and socket. DSN such as mysql:host=localhost;dbname=test plus credentials and options.
Failure reporting Inspect connect_error/connect_errno, or use strict reporting and catch the resulting exception. Throws PDOException when PDO::ATTR_ERRMODE is set to exception mode.
Transport choice localhost selects a Unix socket; an IP or DNS name selects TCP/IP. The DSN’s host and optional port or socket determine the endpoint; do not assume localhost means TCP.
Best diagnostic comparison Match every constructor argument with the successful MySQL client command. Expand the DSN into explicit host, port, database and charset values while troubleshooting.

Neither API can compensate for a server listening somewhere else or an account that lacks permission. Select the API your application already uses, then make its endpoint and error handling explicit.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Follow a repeatable repair sequence

  1. Save the full error privately. Include code 2002 or 2005 when present and copy the host, port and socket text exactly.
  2. Identify the API and PHP runtime. Determine whether the request uses mysqli or PDO and which PHP configuration loads it.
  3. Test the server with the MySQL client. Use identical host, port, username and database; test a socket explicitly when applicable.
  4. Resolve the transport. For a local TCP test, use 127.0.0.1 and the configured port. For a socket test, pass the actual socket path.
  5. Resolve names and network policy. For remote hosts, verify DNS, listener address, route and firewall rules from the PHP machine.
  6. Check account host and privileges. Confirm that the account row matches the transport and source host, then verify database access.
  7. Check the driver. Enable the PDO MySQL or mysqli extension in the PHP runtime handling the request and restart that runtime if required.
  8. Retest with safe logging. Keep detailed errors in server logs and return only a generic failure message to users.

Common symptoms and targeted fixes

“Can’t connect to local MySQL server through socket”

Read the socket path in the message. If it is not the server’s actual socket, supply the correct path or switch to TCP with 127.0.0.1 and the configured port. If the path is correct, confirm that MySQL is running and that the PHP process has permission to reach the socket.

“Connection refused” on 127.0.0.1

Confirm the port and listener address. The server may use a non-default port, listen only on a Unix socket, or be stopped. Test the same address and port with the MySQL client before changing credentials.

Error 2005: unknown host

Correct the hostname and test name resolution from the PHP environment. If DNS is intentionally unavailable, use the approved IP address temporarily while fixing DNS; ensure the account’s host policy still permits that source.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

“Access denied for user”

MySQL was reached, so investigate the password, username, database grants and account host. Remember that switching between localhost and 127.0.0.1 can select different host-specific account rows.

“Could not find driver”

Install or enable the driver matching your API in the web-serving PHP runtime. Verify the loaded configuration and restart the relevant PHP handler. This error is local to PHP and does not demonstrate that MySQL is down.

Production-safe error handling

Development diagnostics should be detailed; production responses should not be. Configure production PHP with display_errors disabled, log connection exceptions or mysqli errors server-side, and return a generic message with an appropriate HTTP status. Restrict log access because exception text can contain usernames, hostnames, database names or socket paths.

Keep secrets outside source control where possible, avoid logging passwords or complete DSNs, and rotate a credential if it was ever exposed in a browser response or public log. Once the connection works, retain the explicit host, port or socket choice so a deployment change does not silently switch transports.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When the same code moves between environments

A connection string that works on a developer laptop may fail on shared hosting, in a container or on a separate database server because the meaning of localhost, available sockets, DNS and account host grants changes with the deployment. Treat environment-specific values as configuration, not hard-coded assumptions.

  • Local development: determine whether the server exposes a socket, TCP, or both, and test the selected endpoint.
  • Containerized PHP: 127.0.0.1 refers to the PHP container itself, not automatically to a separate database container; use the deployment’s configured database hostname and port.
  • Shared hosting: obtain the provider’s exact database host, port and socket information; it may not be the machine’s loopback address.
  • Remote database: use the approved DNS name, confirm network access from the application host, and ensure the MySQL account permits that source host.

Re-run the command-line test from each environment after a deployment change. The successful endpoint and account policy, not a generic preference for sockets or TCP, determine the correct PHP settings.

Final verification checklist

  • The complete original error is recorded privately, including its numeric code.
  • MySQL is running and listening on the endpoint being tested.
  • The MySQL client succeeds with the same host, port or socket, user and database.
  • localhost is used intentionally as a socket endpoint, or an explicit IP/DNS host is used for TCP.
  • The port is the server’s configured port; 3306 is used only when it is actually correct.
  • The socket path matches the server’s socket exactly when a socket is required.
  • The username, password, database and account host grants match the selected transport.
  • The PHP runtime has the required mysqli or PDO MySQL driver enabled.
  • Detailed errors are logged server-side, with generic production responses and no exposed secrets.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.