PHP PDO: charset, set names?

PHP PDO: charset, set names?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Migrating from mysql_* to PDO: Handling Character Sets

When migrating away from the deprecated mysql_* extension, one of the most immediate concerns is how to handle character sets. In your legacy code, you were explicitly calling mysql_set_charset("utf8", $link) followed by mysql_query("SET NAMES 'UTF8'"). This double-step approach was necessary because the mysql_* functions treated the connection charset (the database's default) and the client's current charset as separate entities that often drifted apart.

With PDO, this manual intervention is largely obsolete, but understanding why it changed is critical for writing robust code. The short answer is that you generally do not need to manually set the charset immediately after creating a PDO connection if your configuration is correct. However, there are specific scenarios where you must intervene, and knowing which ones requires precise knowledge of the underlying protocol.

The Default Behavior of PDO

When you instantiate a PDO object using new PDO(), the driver negotiates the character set based on the database server's default for that connection. By default, PDO will execute a SET NAMES equivalent during the handshake phase if the MySQL server sends a charset in the capability flags. This usually aligns the client and server to the database's default collation (often utf8mb4_general_ci or similar).

If your database was created with UTF-8 as the default, your existing PDO code:

$connect = new PDO("mysql:host=$host;dbname=$db", $user, $pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

will likely work perfectly fine without any additional lines. The driver handles the initial handshake, and subsequent queries will execute in UTF-8. You can verify this by running a query that retrieves the current connection charset:

$charset = $connect->query("SHOW VARIABLES LIKE 'character_set_connection'")->fetchColumn();
// This will typically return 'utf8mb4' or 'utf8' depending on your server config.

When You Must Set It Manually

The situation changes if you are connecting to a database that defaults to latin1 (common in older installations) but expects UTF-8 content, or if you need to ensure consistency across different drivers and environments. In these cases, the legacy equivalent of SET NAMES is required to switch the active character set for the current connection session.

You can achieve this using the PDO attribute PDO::MYSQL_ATTR_INIT_COMMAND. This allows you to pass a SQL command that executes immediately after the connection is established but before any user queries.

$connect = new PDO(
    "mysql:host=$host;dbname=$db;charset=utf8mb4", 
    $user, 
    $pass, 
    array(
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4"
    )
)

By including charset=utf8mb4 directly in the DSN (Data Source Name), you force the driver to request that specific character set during the handshake. Combined with the INIT_COMMAND, you ensure that regardless of what the server defaults to, the connection is explicitly aligned to UTF-8 before your application logic begins.

Handling Collation and Encoding Nuances

It is important to distinguish between encoding (e.g., UTF-8) and collation (e.g., utf8mb4_unicode_ci). The SET NAMES command sets the character set, but it also implicitly resets the client's collation. If your application relies on specific sorting behaviors or case-insensitive matching, you must ensure the collation matches your expectations.

Legacy mysql_set_charset() was somewhat aggressive in enforcing both charset and collation. In PDO, if you rely solely on the DSN charset, you might end up with a connection that speaks UTF-8 but uses a different collation than intended. If you require strict control over the collation (e.g., switching from utf8mb4_general_ci to utf8mb4_bin), you should execute a separate query after connection:

$connect->exec("SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci");

This explicit step mirrors the behavior of the old mysql_set_charset() more closely, giving you granular control over how string comparisons work in your queries.

Summary of Best Practices

To summarize the migration path: if your database defaults to UTF-8, PDO's default behavior is usually sufficient. However, for maximum portability and to avoid surprises when moving between environments, explicitly defining charset=utf8mb4 in the DSN and using PDO::MYSQL_ATTR_INIT_COMMAND is a safe pattern. This approach eliminates the "drift" that plagued the legacy mysql_* functions without requiring verbose manual queries after every connection.

For developers working on large-scale applications where consistent character handling is non-negotiable, these explicit settings provide a safety net against encoding issues that often surface only when processing international content or importing data from external sources.

Our network