参见英文答案 > UTF-8 all the way through 14个
我在数据库中的charset设置为utf8_unicode_ci,所有文件都以UTF8编码(没有BOM).
这是我的PHP代码:
require_once("./includes/config.php");
$article = new Article();
$fields = array(
'status' => '0',
'title' => 'מכבי ת"א אלופת אירופה בפעם ה-9',
'shorttitle' => 'מכבי ת"א אלופת אירופה',
'priority' => '1',
'type' => '1',
'category' => '2',
'template' => '68',
'author' => '1',
'date' => date("Y-m-d H:i"),
'lastupdate' => date("Y-m-d H:i"),
'preview' => 'בלה בלה בלה',
'content' => 'עוד קצת בלה בלה בלה',
'tags' => 'מכבי ת"א,יורוליג,אליפות אירופה',
'comments' => '1'
);
$article->set($fields);
$article->save();
出于某种原因,希伯来字符在phpmyadmin中显示如下:
מכבי ת”× ×לופת ×ירופה ×‘×¤×¢× ×”-9
数据库连接代码:
final class Database
{
protected $fields;
protected $con;
public function __construct($host = "", $name = "", $username = "", $password = "")
{
if ($host == "")
{
global $config;
$this->fields = array(
'dbhost' => $config['Database']['host'],
'dbname' => $config['Database']['name'],
'dbusername' => $config['Database']['username'],
'dbpassword' => $config['Database']['password']
);
$this->con = new mysqli($this->fields['dbhost'], $this->fields['dbusername'], $this->fields['dbpassword'], $this->fields['dbname']);
if ($this->con->connect_errno > 0)
die("Database connection error: ".$this->con->connect_error);
}
else
{
$this->con = new mysqli($host, $username, $password, $name);
if ($this->con->connect_errno > 0)
die("Database connection error: ".$this->con->connect_error);
}
}
有什么想法吗?
解决方法:
您已将数据库和文件的字符集设置为UTF-8,但PHP和数据库之间的数据传输也需要正确设置.
您可以使用set_charset执行此操作:
Sets the default character set to be used when sending data from and to the database server.
添加以下内容作为Database构造函数的最后一条语句:
$this->con->set_charset("utf8");
这不会解决数据库中已有数据的问题,但是对于写入数据库的新数据,您应该注意到差异.
如果您决定重建数据库,请考虑使用优秀的utf8mb4字符集,如MySql docs中所述:
The character set named utf8 uses a maximum of three bytes per character and contains only BMP characters. As of MySQL 5.5.3, the utf8mb4 character set uses a maximum of four bytes per character supports supplemental characters:
For a BMP character, utf8 and utf8mb4 have identical storage characteristics: same code values, same encoding, same length.
For a supplementary character, utf8 cannot store the character at all, while utf8mb4 requires four bytes to store it. Since utf8 cannot store the character at all, you do not have any supplementary characters in utf8 columns and you need not worry about converting characters or losing data when upgrading utf8 data from older versions of MySQL.
utf8mb4 is a superset of utf8
标签:php,mysql,character-encoding,mysqli
来源: https://codeday.me/bug/20190824/1706166.html