GET charset with mysql PDO

后端 未结 2 1346
走了就别回头了
走了就别回头了 2021-01-03 02:14

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

相关标签:
2条回答
  • 2021-01-03 02:49

    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.

    0 讨论(0)
  • 2021-01-03 02:53

    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);
    
    0 讨论(0)
提交回复
热议问题