DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk9 min

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

A practical guide to PHP–MySQL connection failures: classify the error, test the same tuple with the MySQL client, resolve localhost versus 127.0.0.1, repair sockets, ports, DNS, grants and drivers, and keep production diagnostics safe.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

PHP–MySQL connection failures become much easier to fix once you identify which layer failed: a local Unix socket, a TCP host or port, DNS name resolution, MySQL authentication and host permissions, or a missing PHP driver. Start by copying the complete error, then test the same host, port, socket, database, user and password with the MySQL command-line client. That separates a server or account problem from PHP configuration.

The most common local mismatch is localhost versus 127.0.0.1. In mysqli, localhost normally selects a Unix-domain socket, while 127.0.0.1 forces TCP/IP. Use the value that matches the listener configured by MySQL, and keep production error details in server-side logs rather than displaying them 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

Do not treat every “can’t connect” message as a bad password. The wording, numeric code and endpoint identify the failing layer. Preserve the entire message, including the host, port or socket path, before making changes.

Failure class Typical clue What to inspect first
Local socket “Can’t connect to local MySQL server through socket …” or error 2002 Whether mysqld is running and whether PHP is using the same socket file
TCP host or port Connection refused, timeout, or a failure after specifying an IP and port MySQL’s listening address, configured port and network rules
DNS Unknown host or error 2005 Hostname spelling, DNS resolution and the server name visible to the PHP runtime
Authentication or host permission “Access denied for user …” after the server responds Username, password, database and the account’s allowed host
Missing PHP driver PDO reports “could not find driver,” or the mysqli class/function is unavailable The PHP extension loaded by the web runtime, not only by the command-line PHP binary

Error 2002 points to a local socket path or local endpoint problem; error 2005 means the host name could not be resolved by the client. An “access denied” response is different: it proves that a MySQL server answered, so changing socket files or firewall rules will not repair the account policy.

Record the complete connection tuple

A connection is determined by six values: host, port, socket (when using a local socket), database name, username and password. The PHP API and the deployment environment add a seventh requirement: the correct driver. Write these values down for the failing request and compare them with the values used by a working client.

  • Host: a DNS name, IPv4 address such as 127.0.0.1, IPv6 address, or localhost.
  • Port: the TCP listener. 3306 is the conventional mysqli/client default only when no other port is supplied.
  • Socket: the Unix-domain socket file selected for local connections.
  • Database: the schema PHP should select after authentication.
  • User and password: credentials that exist on the target MySQL server.
  • Driver: mysqli or PDO with its MySQL driver loaded by the PHP runtime serving the page.

Keep secrets out of tickets and browser output. When comparing configurations, redact the password and any complete DSN that contains it.

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

Test MySQL outside PHP first

Use the MySQL command-line client with the same endpoint and credentials. MySQL’s troubleshooting guidance recommends this test when PHP or another application cannot connect. A successful command-line login shows that the server, route and account can work with those parameters; a failed login gives you a server-side or network problem to solve before debugging PHP.

Test a TCP endpoint

mysql -h 127.0.0.1 -P 3306 -u app_user -p app_database

Enter the password when prompted. Replace the address, port, user and database with the exact values used by PHP. If the server listens on a nonstandard port, specify it explicitly; do not assume 3306.

Test a Unix socket

mysql --socket=/path/to/mysql.sock -u app_user -p app_database

Use the socket path named in the PHP error or in the server configuration. If this command works but the TCP command fails, MySQL is reachable through the socket and your TCP listener or port settings need attention. If TCP works but the socket command fails, PHP is probably selecting the wrong socket.

Interpret the result

  • Connection succeeds: compare PHP’s loaded driver, host, port, socket and credentials character-for-character with the command that worked.
  • Unknown host: correct DNS or the host name before changing MySQL accounts.
  • Connection refused or timed out: verify that MySQL is running and listening on the requested address and port, then check network policy.
  • Access denied: inspect the account’s password and permitted host; transport is already functioning.

Understand localhost versus 127.0.0.1

The PHP mysqli manual gives localhost a special meaning: it is bound to Unix-domain sockets. By contrast, 127.0.0.1 selects TCP/IP. These values are not interchangeable labels for the same route.

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

When to use a socket

A Unix socket is a file on the same machine as the PHP process. It avoids TCP networking and can be the intended local transport. The socket must exist, be accessible to the PHP process, and match the path on which MySQL is listening. A stale path such as /tmp/mysql.sock produces a local-socket error even when mysqld is running.

When to force TCP

Use an explicit loopback address and port when the server is configured for TCP and the socket path is uncertain. This also makes the transport obvious in configuration and logs:

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

The port in the constructor must match MySQL’s TCP listener. If TCP is disabled or a policy allows only the local socket, forcing 127.0.0.1 will fail; switch back to the configured socket instead.

PDO has the same transport choice

A PDO DSN can name a host and port for TCP:

$dsn = 'mysql:host=127.0.0.1;port=3306;dbname=' . $database . ';charset=utf8mb4';

For a socket-only setup, use the socket option supported by your PHP/PDO configuration rather than adding a misleading TCP host. The important point is that the DSN must describe the listener that actually exists.

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.

Fix a local socket error

If the message says “Can’t connect to local MySQL server through socket,” follow this order.

  1. Confirm the server process: verify that the MySQL server is running in the operating system or service manager used by your host. A stopped server cannot create or answer on any socket.
  2. Capture the exact path: copy the socket filename from the error. Common-looking paths are not automatically correct; installations can place the socket elsewhere.
  3. Compare server and PHP settings: find the socket configured for MySQL and the socket value used by PHP. The two paths must be identical.
  4. Check access: ensure the account running PHP can reach the socket file and its parent directory. Permission or confinement rules can block an otherwise valid socket.
  5. Retest directly: run the MySQL client with --socket set to that path, then repeat the PHP request.

If the socket path cannot be made consistent, use TCP explicitly with the server’s actual address and port, provided TCP is enabled and permitted.

Fix TCP host, port and listener problems

A TCP failure means PHP attempted a network connection but did not reach a usable MySQL listener. Check the endpoint as a pair: an address without the correct port is incomplete.

  • Verify that MySQL is listening on the address PHP uses. A server bound only to a private interface will not answer on an unrelated address.
  • Confirm the configured port. 3306 is merely the default used when a mysqli/client port is omitted; deployments may select another port.
  • Use the same host and port with the command-line client. A successful client test proves the route and listener are available from that machine.
  • For a remote database, check firewalls, security groups, container networks and hosting-provider rules that govern inbound traffic.
  • Do not “fix” a timeout by changing credentials. Authentication occurs only after a network connection is established.

In containers or separate virtual machines, 127.0.0.1 means the container or machine running PHP, not the database host. Use the database service name or reachable address supplied by that deployment, and expose only the required port.

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

Fix an unknown MySQL host

Error 2005 identifies an unknown host. The PHP process could not resolve the name to an address, so MySQL never received a login attempt.

  1. Check the spelling, punctuation and environment-variable value for the host name.
  2. Resolve the name from the same machine or container that runs PHP; your workstation’s DNS result may differ.
  3. Use the provider’s internal database name for private networks and its public name only when external access is intentionally enabled.
  4. Retest with the command-line client using the corrected host. Only after name resolution works should you investigate ports or account grants.

A DNS fix does not guarantee access: the resolved address must still have a listening MySQL port and an account permitted from the PHP host.

Fix authentication and host-permission errors

When MySQL returns “Access denied for user,” the transport is working. Verify all account inputs and the host portion of the MySQL account.

Check the credentials and database

  • Ensure PHP is reading the intended environment variables or configuration file, rather than an empty value or an old deployment secret.
  • Confirm capitalization and punctuation in the user name and password.
  • Verify that the requested database exists and that the account has privileges on it. A valid login can still fail when the selected database is unavailable to that account.

Check the account’s allowed host

MySQL accounts include a host component. An account permitted from one source host may be rejected when PHP connects from another address, even with the correct password. Review the account rows and host-name resolution on the MySQL server, then grant the narrowest source host that matches your deployment. Do not broaden access merely to silence an error.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Check the PHP driver and API

PHP must have a MySQL-capable extension loaded by the runtime serving the request. The command-line binary and the web server can load different php.ini files, so checking only CLI PHP can produce a false result.

mysqli

mysqli accepts host, user, password, database, port and socket values. In non-exception mode, inspect connect_error or mysqli_connect_error() immediately after the attempt. For development, strict reporting makes failures visible:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
    $mysqli = new mysqli($host, $user, $password, $database, $port, $socket);
    $mysqli->set_charset('utf8mb4');
} catch (mysqli_sql_exception $e) {
    error_log('MySQL connection failed: ' . $e->getMessage());
}

Pass either the appropriate TCP values or the socket value; do not combine a socket-only setup with an unrelated host and port.

PDO

PDO builds the connection from a DSN and credentials. On failure, it throws PDOException when exception mode is enabled:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
try {
    $pdo = new PDO(
        'mysql:host=127.0.0.1;port=3306;dbname=' . $database . ';charset=utf8mb4',
        $user,
        $password,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );
} catch (PDOException $e) {
    error_log('Database connection failed: ' . $e->getMessage());
    // Return a generic message to the visitor.
}

If PDO reports that it cannot find a driver, install or enable the PDO MySQL extension for the PHP runtime serving the request, then restart that runtime. Package names differ by operating system; verify the loaded configuration rather than copying a platform-specific package command.

Use diagnostics safely in production

Detailed connection errors are valuable to an administrator and dangerous in a browser. They can reveal database names, user names, internal hostnames, socket paths and configuration details.

  • Log the exception or mysqli error on the server, with a timestamp and request identifier if your logging system supports one.
  • Set PHP’s display_errors to 0 in production and return a neutral message such as “The service is temporarily unavailable.”
  • Never print passwords, complete DSNs containing secrets, or internal socket paths.
  • Use verbose exception output only in a controlled development environment and disable it before deployment.

Connection recipes by deployment

Environment Preferred endpoint check Common mistake
Single local machine Test both the configured socket and 127.0.0.1:port with the client Assuming localhost always means TCP
Containerized PHP and MySQL Run the client from the PHP container using the database service name and exposed port Using 127.0.0.1, which points back to the PHP container
Shared hosting Use the host name, port and database name supplied by the hosting control panel Assuming the local socket path from another server applies
Remote managed database Test from the application host, then verify firewall and account source-host rules Testing from a laptop and assuming the application server has the same route

A fast decision path

  1. Copy the complete PHP error and identify whether it names a socket, host, port, DNS failure or access denial.
  2. Run the MySQL client with the same host, port or socket, user and database.
  3. If the client fails, repair the server, endpoint, DNS, network route or account before editing PHP.
  4. If the client succeeds, compare the PHP runtime’s driver, configuration file and connection tuple with the working command.
  5. For local connections, choose deliberately between localhost (Unix socket) and 127.0.0.1 (TCP/IP).
  6. After the fix, keep detailed diagnostics in logs and verify that visitors receive only a generic failure message.

This process avoids random changes: each test narrows the failure to one layer, and the final PHP configuration mirrors an endpoint and account that have already been proven to work.

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.

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

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 from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

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.