GalaxyTramp GalaxyTramp - 5 months ago 37
MySQL Question

UTF-8 encoding problems

I have a site that is storing spanish characters in a MySQL DB. All tables and DB are configured UTF-8 and is identically loaded onto my local WAMP setup and to the hosting account server as much as I can reasonably tell.

Spanish characters display perfectly locally but on the live server the dreaded question mark symbol is displayed for the accented characters. Only the text generated dynamically from the DB is affected so it would be reasonable to assume that this is somehow related to my queries, connection or DB in some way.

<meta charset="utf-8">
<title>Untitled Document</title>
</head>

<select multiple class='form-control' name='location[]' id='location'>
encoding: UTF-8<option value='Alhaur�n de la Torre'>Alhaur�n de la Torre</option>
encoding: ASCII<option value='Artola'>Artola</option>
encoding: ASCII<option value='Bel Air'>Bel Air</option>


Using mb_detect_encoding() my dropdown looks as above.

My header contains:

header('Content-type: text/html; charset=utf-8');


Database is utf8_general_ci for tables, server connection collation, server charset is UTF-8 Unicode (utf8)

I have used SET NAMES utf8 in my PDO DB connection.

This is driving me crazy, why does it work locally but not on my hosting server. After much searching for a n answer I am hoping for some guidance here.

Thanks in advance

SOLVED:

In my connection script I changed this:

$dbh = new PDO("mysql:host=$dbHost;dbname=$dbName;", $dbUser, $dbPass);
$dbh->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, 'SET NAMES utf8');


To this:

$dbh = new PDO("mysql:host=$dbHost;dbname=$dbName;", $dbUser, $dbPass, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));


and all works as it should.

Thanks for looking

Answer

SOLVED:

In my connection script I changed this:

 $dbh = new PDO("mysql:host=$dbHost;dbname=$dbName;", $dbUser, $dbPass);
 $dbh->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, 'SET NAMES utf8');

To this:

 $dbh = new PDO("mysql:host=$dbHost;dbname=$dbName;", $dbUser, $dbPass, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));

and all works as it should.

Thanks for looking

Comments