Problems with ÆØÅ (Norwegian letters) when inserting into database (MySQLi)

I'm having problems when inserting Norwegian letters (æøå) into a database. The charset coding of my document (using Notepad++) is set to UTF-8. The variable that is being inserted has the proper characters, but when it is inserted a word that should be shown as "spørsmål", is when inserted to the database, shown as "spørsmÃ¥l".

I'm using the following code to insert:

$newContent = htmlspecialchars($_POST['newContent']);

$stmt = $mysqli->prepare("UPDATE info SET frontpageText=?");
$stmt->bind_param('s', $newContent);
$stmt->execute(); 
$stmt->close();

And when connecting to the databse, I've tried using

$mysqli->set_charset("utf8");
$mysqli->query("SET NAMES 'utf8'");

I've also done the following:

  • The database collation is set to utf8_danish_ci
  • Using header('Content-type: text/html; charset=utf-8'); (PHP header)
  • Using meta charset="utf-8" (in the HTML-head)
  • The document itself is encoded in utf-8
  • Tried running SET NAMES utf8;

The worst part about this, is that I've actually had it working earlier, but I've appearantly broken something (which I don't know what).

Anyone has an idea what could be done to fix this issue?

EDIT: Problem has been solved. Apparently the table wasn't properly set to UTF-8. Ran this code in phpMyAdmin

ALTER TABLE table_name CHARSET = 'utf8';

Answers


The character set and the collation have separate encodings (one can be latin1 and the other can be utf8).

A character set is a set of symbols and encodings. A collation is a set of rules for comparing characters in a character set. Let's make the distinction clear with an example of an imaginary character set.

To diagnose the encoding of a table this query can be run, where ##TABLENAME## should be the actual table name.

SHOW CREATE TABLE ##TABLENAME##

If the encoding is not utf8 it can be altered with

alter table table_name charset = 'utf8';

Here's a thread on collation vs. character set, What does character set and collation mean exactly?.


You can convert all characters to html chars and save into database that way.

mb_convert_encoding($string, 'HTML-ENTITIES', 'utf-8');

All browsers will display it in the right way.


Make sure the default table charset or field charset is set to utf-8. I know you've said that database charset is set correctly, but tables may interfere with that if they specify a different charset.


Need Your Help

Structuring JSF file in web application

java jsf java-ee

I am making a web application (JSF) and I wonder how to structure the files. I have different resources a user can interact with such as "Questions".

Style inherited control like base control

c# wpf inheritance

In WPF/C# I want to define a new class inheriting from an existing control, but which uses the style of the base control. For example: