0

Possible Duplicate:
PHP : Array key containing special character not found

I am comparing strings to determine corresponding numbers for the strings. The one set of strings is stored in a MySQL DB and the other set of strings are stored as keys for an array in php.

When trying to lookup the following string, it is not found in the array. "Child attending pre-school/nursery school/crèche/day-mother"

More information on the code is available in this previous question that led me to the following test.

After doing a hex dump as suggested, I got the following results

From MySQL DB:

43 68 69 6c 64 20 61 74 74 65 6e 64 69 6e 67 20 70 72 65 2d 73 63 68 6f 6f 6c 2f 6e 75 72 73 65 72 79 20 73 63 68 6f 6f 6c 2f 63 72 e8 63 68 65 2f 64 61 79 2d 6d 6f 74 68 65 72

From string in php:

43 68 69 6c 64 20 61 74 74 65 6e 64 69 6e 67 20 70 72 65 2d 73 63 68 6f 6f 6c 2f 6e 75 72 73 65 72 79 20 73 63 68 6f 6f 6c 2f 63 72 c3 a8 63 68 65 2f 64 61 79 2d 6d 6f 74 68 65 72

The difference was "E8" vs "C3A8" or "è" from the MySQL DB vs "è" from the php string.

So how can I go about ensuring the hard coded php array key character remains "è"?

Community
  • 1
  • 1
Rynardt
  • 5,547
  • 7
  • 31
  • 43

1 Answers1

1

You should use the same enconding in both PHP and MySQL.

If your PHP string is UTF-8 encoded, your tables' charset must be utf8 and the collation should be utf8_general_ci or utf8_unicode_ci. Also, you have to tell MySQL that you want the results you query in UTF-8 too. Here are three ways to achieve this:

  1. Query on connect: Execute SET NAMES utf8 just after connect to MySQL.
  2. Using PDO: $pdo = new PDO($dsn, $user, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'); This is basically the same as above but auto-performed by PDO.
  3. Permanent (my.cnf): This will set UTF-8 implicit for all connections. Just add: init-connect='SET NAMES utf8' to MySQL's config file my.cnf.

I personaly use the 3rd option but in a shared environment I'd choose the 2nd one.

Carlos
  • 4,949
  • 2
  • 20
  • 37
  • Just to note: should you, god forbid, use the older MySQL extensions, always use the appropriate API, e.g. `mysql_set_charset`. Don't run a `SET NAMES` query. – deceze Oct 25 '12 at 07:34