Home > Backend Development > PHP Tutorial > How Do I Set Character Set and Collation in PHP PDO?

How Do I Set Character Set and Collation in PHP PDO?

DDD
Release: 2024-12-23 08:39:15
Original
725 people have browsed it

How Do I Set Character Set and Collation in PHP PDO?

PHP PDO: Character Set and Collation

In the legacy mysql_* API, you used mysql_set_charset() and mysql_query("SET NAMES 'UTF8'") to set the character set and collation. With PDO, these functions are no longer necessary. Instead, you specify the character set and collation in the connection string.

Connection String with Character Set and Collation

The following code shows how to specify the character set and collation in the connection string:

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

This will connect to the database and set the character set to UTF-8.

Prior to PHP 5.3.6

Prior to PHP 5.3.6, the charset option in the connection string was ignored. If you are using an older version of PHP, you must set the character set using the exec() method:

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

The above is the detailed content of How Do I Set Character Set and Collation in PHP PDO?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template