2017-02-16 92 views
0

爲什麼在連接服務器上的mysql客戶端時我可以運行「CHARSET utf8mb4」並更改連接的字符集,但是當我嘗試通過mysqli執行相同的語句時,以下錯誤:無法更改PHP MySQLi連接的字符集

ERROR SQL error in "charset utf8mb4"; 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 'charset utf8mb4' at line 1

回答

1

據我所知,MySQL服務器沒有任何charset命令要麼。用SET NAMES指定字符集,這是一個快捷方式來設置幾個相關變量(無論如何都可以使用SET命令設置所有這些變量)。

你可能與官方命令行客戶端的命令困惑:

mysql> \h 

For information about MySQL products and services, visit: 
    http://www.mysql.com/ 
For developer information, including the MySQL Reference Manual, visit: 
    http://dev.mysql.com/ 
To buy MySQL Enterprise support, training, or other products, visit: 
    https://shop.mysql.com/ 

List of all MySQL commands: 
Note that all text commands must be first on line and end with ';' 
?   (\?) Synonym for `help'. 
clear  (\c) Clear the current input statement. 
connect (\r) Reconnect to the server. Optional arguments are db and host. 
delimiter (\d) Set statement delimiter. 
ego  (\G) Send command to mysql server, display result vertically. 
exit  (\q) Exit mysql. Same as quit. 
go  (\g) Send command to mysql server. 
help  (\h) Display this help. 
notee  (\t) Don't write into outfile. 
print  (\p) Print current command. 
prompt (\R) Change your mysql prompt. 
quit  (\q) Quit mysql. 
rehash (\#) Rebuild completion hash. 
source (\.) Execute an SQL script file. Takes a file name as an argument. 
status (\s) Get status information from the server. 
tee  (\T) Set outfile [to_outfile]. Append everything into given outfile. 
use  (\u) Use another database. Takes database name as argument. 
charset (\C) Switch to another charset. Might be needed for processing binlog with multi-byte charsets. 
warnings (\W) Show warnings after every statement. 
nowarning (\w) Don't show warnings after every statement. 

由於您使用的PHP,而不是命令行客戶端,它不存在。

當然,設置編碼的mysqli方式是mysqli::set_charset()。根據PHP手冊:_注意:這(set_charset)是改變字符集的首選方式

+1

僅供參考使用SET CHARACTER SET utf8mb4;聲明。不建議使用mysqli_query()來設置它(例如SET NAMES utf8)。請參閱MySQL字符集概念部分以獲取更多信息._ – RiggsFolly

0

您可以連接到數據庫

+0

爲什麼我的命令在客戶端中運行,而不是在通過mysqli運行時運行?你的命令確實有效,但我想知道爲什麼我的工作不起作用 – thatidiotguy

+1

請參閱接受答案的解釋。 –

+0

@AlexSlipknot - 「SET NAMES」設置3個設置。你的建議只設置其中的一個,並且會導致我不想調試的神祕問題。 –