MySQLで文字化けを防ぐ方法

MySQLで文字化けを防ぐには、SQLの実行前に次のSQLを実行します。

SET NAMES utf8

[参考記事] SET NAMESで文字セットを変更することは推奨されません

CakePHPでは、app/config/database.phpのDB接続設定に

'encoding'=>'文字コード'

を追加します。
これを追加することで、DB接続直後にSET NAMESが実行されます。

具体的には次のようになります。

class DATABASE_CONFIG {

  var $default = array(
    'driver' => 'mysql',
    'persistent' => false,
    'host' => 'localhost',
    'login' => 'user',
    'password' => 'password',
    'database' => 'dbname',
    'port' => '3306',
    'prefix' => '',
    'encoding' => 'utf8'
  );
}

この設定をすることで
/cake/libs/model/datasources/dbo/dbo_mysql.php
で、次のようにSET NAMESが実行されます。

/**
 * Connects to the database using options in the given configuration array.
 *
 * @return boolean True if the database could be connected, else false
 */
  function connect() {
    $config = $this->config;
    $this->connected = false;

    if (!$config['persistent']) {
      $this->connection = mysql_connect($config['host'] . ':' . $config['port'], $config['login'], $config['password'], true);
      $config['connect'] = 'mysql_connect';
    } else {
      $this->connection = mysql_pconnect($config['host'] . ':' . $config['port'], $config['login'], $config['password']);
    }

    if (mysql_select_db($config['database'], $this->connection)) {
      $this->connected = true;
    }

    if (!empty($config['encoding'])) {
      $this->setEncoding($config['encoding']);
    }

    $this->_useAlias = (bool)version_compare(mysql_get_server_info($this->connection), "4.1", ">=");

    return $this->connected;
  }
/**
 * Sets the database encoding
 *
 * @param string $enc Database encoding
 */
  function setEncoding($enc) {
    return $this->_execute('SET NAMES ' . $enc) != false;
  }

関連記事

スポンサーリンク

<STRIKE> 打ち消し線を引く

ホームページ製作・web系アプリ系の製作案件募集中です。

上に戻る