在数据库中设置utf8 - 我可以从php代码中删除SET NAMES utf8

时间:2015-10-09 17:38:15

标签: php mysql utf-8 character-encoding

我在mysql数据库中设置了utf8

现在显示

+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8                       |
| character_set_connection | utf8                       |
| character_set_database   | utf8                       |
| character_set_filesystem | binary                     |
| character_set_results    | utf8                       |
| character_set_server     | utf8                       |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+


+----------------------+-----------------+
| Variable_name        | Value           |
+----------------------+-----------------+
| collation_connection | utf8_general_ci |
| collation_database   | utf8_unicode_ci |
| collation_server     | utf8_unicode_ci |
+----------------------+-----------------+

我在PHP代码中有以下内容

mysql_query("SET NAMES 'utf8'");

$database = mysqli_connect('host','user','pass','database');
mysqli_query($database,"SET NAMES 'utf8'");

由于我在数据库中设置了utf8,我可以从代码中删除mysql_query("SET NAMES 'utf8'")mysqli_query($database,"SET NAMES 'utf8'")吗?

1 个答案:

答案 0 :(得分:1)

您可以使用mysqli_set_charset

<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

// Change character set to utf8
mysqli_set_charset($con,"utf8");

mysqli_close($con);
?>