Daniel Sharp
Daniel Sharp

Reputation: 169

PHP UTF-8 Encoding MYSQL Inserts?

I have a very strange behaviour that I'm experiencing. When I run insert into with an UTF8 Character (specifically the 'ő' or 'ű' hungarian characters) it inserts a ? instead of the character. However if I echo it out right before passing into the query it shows the right characters.

What I have done:

What works as intended:

It's working on a localhost server. The non local server's default encoding is ISO-8859-1 which I can't change.

Upvotes: 2

Views: 867

Answers (1)

Andre Chenier
Andre Chenier

Reputation: 1186

if you

1 - set your html page's lang encoding to utf-8 which includes your forms
2 - only use your forms to enter input into your related MySQL db tables
3 - set all collations to utf8_unicode_ci in your MySQL (tables and rows collations)
4 - if you have premission you can also setyour MySQL DB collation as utf8_unicode_ci

then you won't see entities in your mySQL records also

This is my solution I use and have no trouble with my mother language which also has lots of unicode characters.

Below I introduce you my db connection php code & recommend (by using prepared statements; please check http://php.net/manual/en/mysqli.quickstart.prepared-statements.php)

//mysql bağlantısı
global $db_baglanti;
$db_baglanti = new mysqli(vt_host, vt_user, vt_password, vt_name);
if ($db_baglanti->connect_errno) 
{
    echo "MySQL bağlantısı kurulamadı: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$db_baglanti->set_charset("utf8")) 
{
    printf("utf8 karakter setinin yüklenmesinde problem oluştu: %s\n", $db_baglanti->error);
} 
else 
{
    $db_baglanti->set_charset("utf8");
}

I think main point for you is number 2 in list above.

Also If you already have some document, edit your document's meta tag for charset declaration and use notepad++ encoding>convert to UTF-8 without BOM, save your document, safely go on with your UTF-8 characters from now on. (this is a solution for possible HTML side issues related to BOM)

Upvotes: 1

Related Questions