简体   繁体   English

将UTF-8字符串插入MySQL表

[英]INSERTing UTF-8 string into MySQL table

I am struggling to INSERT a UTF-8 encoded string into MySQL table from a PHP script: 我正在努力从PHP脚本中将UTF-8编码的字符串插入MySQL表:

The table is set to collation "utf8_unicode_ci", the field is a text field, also collation "utf8_unicode_ci". 该表设置为归类“ utf8_unicode_ci”,该字段是文本字段,也归类为“ 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. ...在INSERT之前一切都看起来不错。 If I echo($str); 如果我echo($ str); I see the unicode characters: 我看到了unicode字符:

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: ...但是当我尝试将此字符串插入MySQL表时,如下所示:

$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? 我很确定表是正确的,(因为我尝试通过PhpMyAdmin插入相同的字符串,并且工作正常),而且我很确定源字符串是正确的,(因为我可以通过echo()输出它,在unicode中),所以我猜问题一定是我插入它的方式吗? What am I doing wrong? 我究竟做错了什么?

PS. PS。 I tried it without the addslashes() on the $str, but then I just get the error: 我没有在$ str上使用addlashes()进行尝试,但是随后我得到了错误:

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! 感谢您的光临!

使用mysqli_set_charset将连接上的字符集设置为UTF-8。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM