使用 MySQLi 设置字符集

2021-12-25 00:00:00 php mysqli

我正在使用 MySQLi 从 MySQL 表中获取阿拉伯语数据.所以我通常在程序风格中使用它:

I'm fetching data in Arabic from MySQL tables with MySQLi. So I usually use this in procedural style:

mysql_query("SET NAMES 'utf8'"); 
mysql_query('SET CHARACTER SET utf8'); 

现在我使用的是 OOP 风格,所以我想看看是否有我可以设置的东西而不是上面的东西?

Now I am using the OOP style so I am trying to see if there is something I could set rather than the above?

我只在 PHP 手册中找到了这个,所以我做了,但是将名称设置为 UTF8 怎么样?

I only found this in PHP manual so I did it, but what about setting names to UTF8?

$mysqli->set_charset("utf8");

推荐答案

都一样:

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

来自手册:

这是更改字符集的首选方法.使用 mysqli::query()不建议执行 SET NAMES ..

This is the preferred way to change the charset. Using mysqli::query() to execute SET NAMES .. is not recommended.

$mysqli->set_charset("utf8"); 就够了,让 mysqli db driver 为你做这件事.

$mysqli->set_charset("utf8"); is just enough, let the mysqli db driver do the thing for you.

相关文章