58
55

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MySQLとPDOの組み合わせでcharsetを指定する

Last updated at Posted at 2012-12-26

mysql関数の場合はmysql_set_charset関数でOK。

PDOでMySQLを使う場合は、PHP 5.3.6からDSNでcharsetを指定できるようになっているので、PDOのインスタンスを作るときにcharsetをきちんと指定してあげる。

<?php
$pdo = new PDO(
    'mysql:host=yourhost;dbname=yourdb;charset=utf8mb4',
    'user', 'password'
);

PHP 5.3.6より前のバージョンをどうしても使わなければいけない場合は次のようにする。

<?php
$options = array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4',
); 
$pdo = new PDO(
    'mysql:host=yourhost;dbname=yourdb',
    'user', 'password', $options
);

いつの間にかPHPのマニュアルにMySQLの文字セット指定についてのページが追加されてた。

58
55
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
58
55

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?