Home > Database > Mysql Tutorial > How Do I Set Character Encoding in PHP PDO Connections?

How Do I Set Character Encoding in PHP PDO Connections?

Linda Hamilton
Release: 2024-12-13 14:07:12
Original
154 people have browsed it

How Do I Set Character Encoding in PHP PDO Connections?

PHP PDO: Character Encoding

Previously, in MySQL_* connections, character encoding was typically set using mysql_set_charset() and mysql_query(). However, these functions are not applicable to PDO connections.

PDO Connection String

For PDO, character encoding can be specified within the connection string itself. Add the charset attribute followed by the desired character set, for example:

"mysql:host=$host;dbname=$db;charset=utf8mb4"
Copy after login

PHP Versions Prior to 5.3.6

In PHP versions prior to 5.3.6, the charset attribute was ignored in the connection string. To set character encoding in these versions, you can use the following approach:

$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password);
$dbh->exec("set names utf8mb4");
Copy after login

This ensures that the character encoding is set for the PDO connection, allowing for proper handling of character data.

The above is the detailed content of How Do I Set Character Encoding in PHP PDO Connections?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template