Felix Hindemo
Felix Hindemo

Reputation: 3

MySQL query returning non UTF8 characters

I've got a login screen that checks entered username and password against a MySQL database. My problem is that it doesn't recognize Swedish characters like "ÅÄÖ".

For example, the password "lösenord" is in the database but it isn't accepted, however "losenord" is.

The database has "utf8_general_ci" connection collation and I've set the charset to UTF-8 in my index.html but not in my php scripts. I've read what feels like a million different ways to solve UTF 8 issues like this but I can't get it to work.

If someone could at least point me in the right direction I would be very thankful. Do I need to encode each mysql query, set some META tag?

Cheers

Upvotes: 0

Views: 3289

Answers (1)

user4035
user4035

Reputation: 23759

Try using SET NAMES 'UTF8' after connecting to MySQL:

$con=mysqli_connect("host", "user", "pw", "db");   
if (!$con)
{
    die('Failed to connect to mySQL: ' .mysqli_connect_errno());
}

/* change character set to utf8 */
if (!$con->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $con->error);
}

As the manual says:

SET NAMES indicates what character set the client will use to send SQL statements to the server... It also specifies the character set that the server should use for sending results back to the client.

Also use utf8_swedish_ci in your table, otherwise string comparison will go wrong and MySQL will treat 'ö' and 'o' as the same character.

Upvotes: 4

Related Questions