0

I have Japanese on my site coming from a mysql database.

Other Japanese text on the site displays fine, but the stuff coming out of the database looks like:

 ????????

The database is set to UTF8, so is the web page.

To fix the issue, before I make any calls to the database I use:

$db->query("SET NAMES utf8");

I was wondering if there was a better/easier way to do the above without having to set names before every query?

Evan Harper
  • 430
  • 3
  • 15
panthro
  • 22,779
  • 66
  • 183
  • 324
  • So, `SET NAMES utf8` fixes the issue or not? (All decent DB libraries allow to set client encoding, check the documentation for yours.) – Álvaro González Mar 13 '13 at 15:11
  • Set set names does fix the issue, i was just wondering if there was a better way. – panthro Mar 13 '13 at 15:23
  • 1
    You only need that once per connection, not before every query. Also, if you use [PDO](http://php.net/pdo), you can configure it so that it does that automatically for you. – Fabian Schmengler Mar 13 '13 at 15:25

1 Answers1

1

You don't have to use SET NAMES utf8 before every query, you just have to run it once the connection is established. Here's an example with PDO :

try {
    $dns  = "mysql:host={HOST};dbname={DB}";
    $user = "{USER}";
    $pass = "{PASS}";
    $con = new PDO($dns, $user, $pass);
} catch ( Exception $e ) {
    echo "Connexion error ", $e->getMessage();
    die();
}

$con->query("SET NAMES utf8;");
//and now, as many queries as you want

If you're using PHP >= 5.3.6, you can define the charset in the connection string (prior PHP versions ignore it) :

try {
    $dns  = "mysql:host={HOST};dbname={DB};charset=utf8";
    $user = "{USER}";
    $pass = "{PASS}";
    $con = new PDO($dns, $user, $pass);
} catch ( Exception $e ) {
    echo "Connexion error ", $e->getMessage();
    die();
}

//and now, as many queries as you want
zessx
  • 68,042
  • 28
  • 135
  • 158