I am trying to fetch "hindi" (utf-8) results from MySQL database using php.
I have written the following code..
<?php
$connection = mysql_connect("localhost","root","root");
if(!connection)
{
die('Could not connect: ' . mysql_error());
}
mysql_query('SET character_set_results=utf8');
mysql_query('SET name=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_results=utf8');
mysql_query('SET collation_connection=utf8_general_ci');
mysql_select_db('data',$connection);
$result = mysql_query("SET NAMES utf8");
$cmd = "select * from question";
$result = mysql_query($cmd);
$myArray = array();
while($row =$result->fetch_object()){
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
?>
But I am not getting the expected results. I want to print Utf-8(Hindi) data.
if I use the following code to print individual row then
while($myrow = mysql_fetch_row($result)){
echo ($myrow[0]);
echo ($myrow[1]);
echo ($myrow[2]);
}
It works fine and prints the utf-8(Hindi) data.
Please help me what I am missing or is there anything wrong implemented....
Thanks in advance..!!
mysql_query('SET name=utf8');
Should be mysql_query('SET NAMES utf8');
. The other SETs are not needed.
Also, don't use the deprecated mysql_* interface, rewrite to use mysqli_* (or PDO).
By Hindi, do you mean DEVANAGARI, such as हिन्दी
?
The utf8 hex for that is: E0A4B9 E0A4BF E0A4A8 E0A58D E0A4A6 E0A580
If you see something like हिनà¥à¤¦à¥€
, you have "Mojibake".
not getting the expected results
What are you getting?
json_encode
-- should include a second argument of JSON_UNESCAPED_UNICODE
to avoid getting the "html entities".
To see hex in PHP,
$hex = unpack('H*', $text);
echo implode('', $hex);
latin1
will not suffice; you need utf8
(or utf8mb4
).
I realize this is not a full or coherent answer, but it presents several action items for the OP to get closer to the solution.