gpt4 book ai didi

php - 设置字符集/排序规则 MySQL PHP?

转载 作者:行者123 更新时间:2023-12-01 14:59:42 26 4
gpt4 key购买 nike

如何设置MySQL连接的排序规则?

// Here is default/Expected output
mysqli_get_charset($con);
object(stdClass)[2]
public 'charset' => string 'utf8mb4' (length=7)
public 'collation' => string 'utf8mb4_unicode_ci' (length=18)
public 'dir' => string '' (length=0)
public 'min_length' => int 1
public 'max_length' => int 4
public 'number' => int 224
public 'state' => int 1
public 'comment' => string '' (length=0)

mysqli_character_set_name($con);
\tests\db.php:22:string 'utf8mb4' (length=7)

设置字符集后使用:

mysqli_set_charset($con, 'utf8mb4');

// Output :

mysqli_get_charset($con);
object(stdClass)[2]
public 'charset' => string 'utf8mb4' (length=7)
public 'collation' => string 'utf8mb4_general_ci' (length=18)
public 'dir' => string '' (length=0)
public 'min_length' => int 1
public 'max_length' => int 4
public 'number' => int 45
public 'state' => int 1
public 'comment' => string 'UTF-8 Unicode' (length=13)

mysqli_character_set_name($con);
\tests\db.php:22:string 'utf8mb4' (length=7)

尝试使用这些:

mysqli_set_charset($con, 'utf8mb4');
mysqli_query($con, "SET NAMES 'utf8mb4';");
mysqli_query($con, "SET CHARACTER SET 'utf8mb4';");
mysqli_query($con, "SET COLLATION_CONNECTION = 'utf8mb4_unicode_ci';");

使用 mysqli_set_charset($con, 'utf8mb4'); 之后

归类重置为 utf8mb4_general_ci

任何防止这种情况发生的方法。

我该如何解决这个问题?

最佳答案

我相信您不关心client 排序规则。

客户端上与字符集相关的唯一用途是转义函数,但它仅使用字符集,而不关心仅在服务器上使用的排序规则。

因此,如果需要设置特定的排序规则,正确的代码应该是

mysqli_set_charset($con, 'utf8mb4');
mysqli_query($con, "SET COLLATION_CONNECTION = 'utf8mb4_unicode_ci'");

在此之后,将设置正确的字符集和排序规则。

您可以使用以下代码进行测试:

var_dump(mysqli_get_charset($con)->collation,$con->query("select @@collation_connection")->fetch_row()[0]);
mysqli_set_charset($con, 'utf8mb4');
var_dump(mysqli_get_charset($con)->collation,$con->query("select @@collation_connection")->fetch_row()[0]);
mysqli_query($con, "SET COLLATION_CONNECTION = 'utf8mb4_unicode_ci'");
var_dump(mysqli_get_charset($con)->collation,$con->query("select @@collation_connection")->fetch_row()[0]);

对我来说它输出

string(17) "latin1_swedish_ci"
string(17) "latin1_swedish_ci"
string(18) "utf8mb4_general_ci"
string(18) "utf8mb4_general_ci"
string(18) "utf8mb4_general_ci"
string(18) "utf8mb4_unicode_ci"

最后一个 - connection 排序规则是您实际需要的。

关于php - 设置字符集/排序规则 MySQL PHP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60430619/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com