關於php讀mysql資料庫時出現亂碼的解決方案

來源:互聯網
上載者:User

標籤:

關於php讀mysql資料庫時出現亂碼的解決方案

php讀mysql時,有以下幾個地方涉及到了字元集。
1.建立資料庫表時指定資料庫表的字元集。例如

  • create table tablename
  • (
  • id int not null auto_increment,
  • title varchar(20) not null,
  • primary key (‘id‘)
  • )DEFAULT CHARSET =UTF8;

複製代碼
2. mysql的字元集
mysql中有三個重要的變數,character_set_client,character_set_results,character_set_connection。
通過設定character_set_client,告訴Mysql,PHP存進資料庫的是什麼編碼方式。
通過設定character_set_results,告訴Mysql,PHP需要取什麼樣編碼的資料。
通過設定character_set_connection,告訴Mysql,PHP查詢中的文本,使用什麼編碼。

3. 串連資料庫後,設定資料庫間傳輸字元時所用的預設字元編碼。
使用mysqli::set_charset()或mysqli::query(‘set names utf8‘),進行設定。
盡量使用mysqli::set_charset(mysqli:set_charset)而不是”SET NAMES”
  • $db = new mysqli(‘localhost‘,‘user‘,‘passwd‘,‘database_name‘);
  • $db->set_charset(‘utf8‘);

複製代碼
注意是utf8,不是utf-8
(這裡有個問題就是,資料庫和php都已經統一了編碼,但是如果沒有調用mysqli::set_charset()函數時,讀出資料時仍然會出現亂碼。這是為什嗎?)
(另,set names utf8相當於下面三句
SET character_set_client = utf8;
SET character_set_results = utf8; 
SET character_set_connection = utf8; 

4. html頁面使用的字元集。在meta標籤中設定
  • <meta http-equiv="content-type" content="text/html; charset=utf-8">

複製代碼
5. php文字檔所使用的字元集。
在linux下可以用vim開啟檔案,輸入
:set encoding
查看檔案使用的字元集

要保證不亂碼,需要保證檔案自身的編碼,HTML裡指定的編碼,PHP告訴Mysql的編碼(包括character_set_client和character_set_results)統一。同時使用mysqli:set_charset()函數或”SET NAMES”。


針對“3”後面的問題,寫了幾個例子,測試連結資料庫後,設定和不設定字元集時的結果。測試環境Ubuntu 12.04,MySQL 5.5,php 5.5.7。
結果如下:
(1) 資料庫表字元集是utf8,不使用set names utf8
能正常插入、讀出中文,但是在mysql中顯示亂碼

(2) 資料庫表字元集是utf8,使用set names utf8
能正常插入、讀出中文,mysql中顯示正確

(3) 資料庫表字元集不是utf8,使用set names utf8
mysql中顯示,讀出都是問號。

 php教程選自零零H5

關於php讀mysql資料庫時出現亂碼的解決方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.