Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO equivalent of mysql_client_encoding()?

Is there any way in PDO to check the client encoding, like there was in mysql/mysqli with mysql_client_encoding();?

On PHP.net it states that one can set the charset with PDO::setAttribute(), e.g.:

$db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");

But how does one get the current charset?

like image 959
Joachim Avatar asked Sep 01 '26 10:09

Joachim


1 Answers

There are two different character sets at issue:

  • the encoding in which MySQL assumes strings are sent by the client (character_set_client); and
  • the encoding in which MySQL will send its responses (character_set_results).

To ascertain the current value of these variables using PDO, you could fetch the results of the relevant SHOW VARIABLES statement; for example:

$qry = $db->query("SHOW VARIABLES LIKE 'character_set_client'");

The documentation for mysql_client_encoding() is somewhat ambiguous, as it states:

Retrieves the character_set variable from MySQL.

However, no such server system variable exists: so I'm not sure which it would return.

Finally, rather than setting a MYSQL_ATTR_INIT_COMMAND, you can specify your desired character set in the DSN (as mentioned in the manual):

$db = new PDO("mysql:dbname=$db;host=$host;charset=$charset", $user, $password);
like image 109
eggyal Avatar answered Sep 04 '26 13:09

eggyal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!