Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GET charset with mysql PDO

Tags:

php

mysql

pdo

Is there a way of retrieving the current character set with PDO? I used to have a little test with Mysqli to check if the forced character set was set by retrieving it like so:

$mysqli->get_charset(); 

That doesn't work on $conn = new PDO();

Any help is appreciated. I'm fairly new to PDO and trying to jump over from mysqli.

P.s. i am aware how to set the character set, just want to test how to retrieve it.

Thanks to HD answering the question I made his method static, perhaps its helpful for someone (I used some prior to 5.4 notation):

 public static function getCharset(PDO $objPdo) {      
  $objCharset = $objPdo->query("SELECT COLLATION('foo')");
  $charset = $objCharset->fetch(PDO::FETCH_NUM);
  return $charset[0];
 }
like image 604
rinserepeat Avatar asked Sep 30 '14 15:09

rinserepeat


2 Answers

If we run the following MySQL query;

mysql> SELECT COLLATION('foo');
+-----------------------+
| COLLATION('foo')      |
+-----------------------+
| utf8_general_ci       |
+-----------------------+
1 row in set

So, we can use the following to get the charset

$objCharset = $objPdo->query("SELECT COLLATION('foo')");
echo $objCharset->fetch(PDO::FETCH_NUM)[0]; //Output: utf8_general_ci
  • PDO Query
  • PDO Fetch
  • Cubrid thread

You can then go a step further, and use the following (with object injection).

<?php 

class foo {
   public function get_charset($objPdo) {
      $objCharset = $objPdo->query("SELECT COLLATION('foo')");
      return $objCharset->fetch(PDO::FETCH_NUM)[0];
   }
}

$objFoo = new foo();
$objPDO = new PDO(...);
echo $objFoo->get_charset($objPDO);
like image 79
ʰᵈˑ Avatar answered Sep 24 '22 19:09

ʰᵈˑ


If you want the actual charset (not collation) you can do this:

$charset = $pdo->query("SELECT CHARSET('')")->fetchColumn();
if($charset === 'utf8mb4') {
    $charset = 'utf8';
}

I put the utf8mb4 check in there because it's not compatible with PHP's mb_ functions.

like image 31
mpen Avatar answered Sep 22 '22 19:09

mpen