Siddharthan Asokan
Siddharthan Asokan

Reputation: 4441

Unicode characters encoding for a MySQL output

I'm trying to retrieve data from a table whose collation is 'utf8_general_ci' and the column titled 'app_name' has string like : Plants vs. Zombies™ 2,포코팡 for Kakao,네이버 - Naver,µTorrent® - Torrent App. When I tried to query the table as below:

   <?php

   $con = mysql_connect('localhost', 'root', 'root') or die('Error connecting to server');

   mysql_select_db('googleappanalysis', $con); 

  if(isset($_POST['appType']))
  {
    $appType = $_POST['appType'];
    $month = $_POST['month'];
    $year = $_POST['year'];
  }


  $monthYear = $month.$year; 

  mysql_query("SET NAMES utf8")

  if($appType == "Apps with IA" ){
    $sql="SELECT app_name  FROM MonthlyAppState WHERE is86 = 1 AND is86 IS NOT NULL AND monthYear = '".$monthYear."'";

    $result=mysql_query($sql);
   }elseif($appType == "Apps with no IA" ){
    $sql="SELECT app_name  FROM MonthlyAppState WHERE is86 = 0 AND is86 IS NOT NULL AND monthYear = '".$monthYear."'";
    $result=mysql_query($sql);
   }


    $table = array();
    $table['cols'] = array(
array('label' => $appType, 'type' => 'string')
 );


 $rows = array();
 $appendingString = "";
 while($r = mysql_fetch_assoc($result)){

    $temp = array();
$temp[] = array('v' => (string)$r['app_name']);
$rows[] = array('c' => $temp);
    $appendingString = $appendingString."/".$r['app_name'];
 }

 $myFile = "logfile.txt";  
 $fh = fopen($myFile, 'w') or die("can't open file"); 
 fwrite($fh, $appendingString);
 fclose($fh);

 $table['rows'] = $rows;

 // encode the table as JSON
 $jsonTable = json_encode($table);

  // set up header; first two prevent IE from caching queries
 header('Cache-Control: no-cache, must-revalidate');
 header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
 header('Content-type: application/json');

 echo $jsonTable;
 ?>

The jsontable throws null values and for the file 'logfile.txt'the unicode characters is converted to '???' as seen here

Upvotes: 2

Views: 380

Answers (1)

zerkms
zerkms

Reputation: 254926

Use

mysql_set_charset('utf8', $con);

right after mysql_connect to set your client character set.

References:

Upvotes: 3

Related Questions