0

I am struggling to INSERT a UTF-8 encoded string into MySQL table from a PHP script:

The table is set to collation "utf8_unicode_ci", the field is a text field, also collation "utf8_unicode_ci". The string is being read in from another site, and looks like this:

$str = "Bonka bдver, е hцra va man bara ta't en fika.";

...everything looks good right before the INSERT. If I echo($str); I see the unicode characters:

Bonka bдver, е hцra va man bara ta't en fika.

...but when I try to INSERT this string into the MySQL table, like this:

$sql = "INSERT INTO mytable (id, mystring)
        VALUES ('','".addslashes($str)."');";
if ( !mysqli_query( $mysqli, $sql ) ) {
    printf("Error: %s\n", mysqli_error( $mysqli ) );
    die();
}

...what gets written to the database is:

Bonka bдver, е hцra va man bara ta't en fika.

I'm pretty sure the table is alright, (because I tried inserting the same string via PhpMyAdmin and it worked fine), and I'm pretty sure the source string is alright, (because I can output it via echo() and it's in unicode), so I guess the problem must be the way that I am inserting it? What am I doing wrong?

PS. I tried it without the addslashes() on the $str, but then I just get the error:

Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 't en fika.

Thanks for looking!

2
  • 1
    Maybe this link will help you. stackoverflow.com/questions/3811257/… Commented Feb 12, 2014 at 23:52
  • Thanks @Newbi3 - found the answer now thanks to Niet, but this link also provides the correct answer. Commented Feb 13, 2014 at 0:01

1 Answer 1

1

Set the charset on the connection to UTF-8 with mysqli_set_charset.

Sign up to request clarification or add additional context in comments.

2 Comments

Brilliant, works! Thanks, I spent the last 4 hours on this... ;-) So I guess setting the collation to unicode wasn't enough!
's one of the main reasons I work purely in single-byte character sets. There's just too much work involved in making things work in UTF-8!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.