Thursday, July 22, 2010

PHP reading from 2 mysql databases with different encoding

I came across a problem of reading data from 2 mySQL databases
one with latin1 encoding and have Arabic char
The other is in UTF encoding and have Arabic Char
the final php page is using UTF encoding
i tried allot and I searched allot for a solution and i came to this solution
i have only one user having access to both databases
code below:
// open database 1
$dbc = mysql_connect (DB_HOST, DB_USER, DB_PASSWORD);
$var_select=mysql_select_db (DB_NAME1);
//first read the data from the latin1
mysql_query("SET NAMES latin1;");
mysql_query("SET CHARACTER_SET latin1;");
mysql_query("SET character_set_client=latin1");
mysql_query("SET character_set_connection=latin1");
mysql_query("SET character_set_database=latin1");
mysql_query("SET character_set_results=latin1");
mysql_query("SET character_set_server=latin1");
$query1="SELECT quesr";
$result1=mysql_query($query1);
$ris1=mysql_fetch_row($result1);
$datalatin1=$ris1[0];
// convert data to utf
$datalatin1=$user=iconv("windows-1256","utf-8", $datalatin1);
//first read the data from the UTF
mysql_query("SET NAMES utf8;");
mysql_query("SET CHARACTER_SET utf8;");
mysql_query("SET character_set_client=utf8");
mysql_query("SET character_set_connection=utf8");
mysql_query("SET character_set_database=utf8");
mysql_query("SET character_set_results=utf8");
mysql_query("SET character_set_server=utf8");
$query="SELECT quesr";
// can use the converted $datalatin1 in the query as it's not UTF
$result=mysql_query($query);
$ris=mysql_fetch_row($result);
$datautf1=$ris[0];

No comments: