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.
Need a server to try this on? Antihost offers Linux VPS plans with NVMe storage, full root access and a 14-day free trial.
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.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errorsClassify 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.
#1 Best Overall
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, orlocalhost. - 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.
Recommended Free Tools
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.
Rank #2
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.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteWhen 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.
Fix a local socket error
If the message says “Can’t connect to local MySQL server through socket,” follow this order.
- 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.
- Capture the exact path: copy the socket filename from the error. Common-looking paths are not automatically correct; installations can place the socket elsewhere.
- Compare server and PHP settings: find the socket configured for MySQL and the socket value used by PHP. The two paths must be identical.
- 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.
- Retest directly: run the MySQL client with
--socketset 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.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →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.
- Check the spelling, punctuation and environment-variable value for the host name.
- Resolve the name from the same machine or container that runs PHP; your workstation’s DNS result may differ.
- Use the provider’s internal database name for private networks and its public name only when external access is intentionally enabled.
- 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.
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:
Best Value
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:
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_errorsto0in 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
- Copy the complete PHP error and identify whether it names a socket, host, port, DNS failure or access denial.
- Run the MySQL client with the same host, port or socket, user and database.
- If the client fails, repair the server, endpoint, DNS, network route or account before editing PHP.
- If the client succeeds, compare the PHP runtime’s driver, configuration file and connection tuple with the working command.
- For local connections, choose deliberately between
localhost(Unix socket) and127.0.0.1(TCP/IP). - 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.
Quick Recap
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.




