PHP Mysql UTF8 arabic CRUD database
To read ,write and sort Arabic text in mysql database using php correctly, make sure that:
1- MySQL charset: UTF-8 Unicode (utf8)
2- MySQL connection collation: utf8_general_ci
3- your database and table collations are set to: utf8_general_ci or utf8_unicode_ci
Then, add this code in your php database connect script :
mysql_query(“SET NAMES ‘utf8′”);
mysql_query(‘SET CHARACTER SET utf8’);
For Example :
function connect() /* {{{ */ { if (isset($this->dbh)) { mysql_query("SET CHARACTER SET 'utf8'", $this->dbh); mysql_query("set names utf8 ", $this->dbh); mysql_query("SET NAMES 'utf8'"); mysql_query('SET CHARACTER SET utf8'); return true; }
Create an UTF8 mysql databases
Create an unicode database with the collation utf8_ci_general :
CREATE TABLE `t1_test` ( `c1_utf8` varchar(50) character set utf8 default NULL, `c2_eng` varchar(50) default NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `t1_test` -- INSERT INTO `t1_test` VALUES ('كيف الحال', 'test2');
To have the right display for arabic under your browser for a unicode database :
In case of a PHP APACHE script:
<?php header("Content-Type: text/html; charset=utf-8"); ?>
In case of an HTML page :
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
Now you can create a small script to test the output or go directly in phpmyAdmin.
Cheers,