getting error while fetch "hindi" results from database using php - php

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.

Related

PHP: json_encode() doesn't show anything with multidimensional array

I'm trying to make a simple PHP script that fetches a table from my MySQL database and encodes the results in JSON, so I can use them later in Java.
This is my code:
<?php
$servername = "localhost:3036";
$username = "example_user";
$password = "example_password";
$conn = mysql_connect($servername, $username, $password);
if(! $conn) {
die("Could not connect: " . mysql_error());
}
$sql = "SELECT * FROM table_name";
mysql_select_db("database_name");
$retval = mysql_query($sql, $conn);
if(! $retval) {
die("Could not get data: " . mysql_error());
}
while($row = mysql_fetch_assoc($retval)) {
$output[]=$row;
}
print(json_encode($output));
mysql_close($conn);
?>
This just gives a blank page as output (error messages are set to display).
However, if I change json_encode($output) to json_encode($output[0]) (or any other number within the array's bounds), the output becomes that one $row array.
This is probably a really stupid question, but after about 3 hours of research I'm at my wit's end. Thank you for any help.
User #Joni led me to the solution.
Adding mysql_set_charset("utf8") fixed my issue.
As mentioned in this post: Why is this PHP call to json_encode silently failing - inability to handle single quotes?.
Try
echo json_encode($output) ;
It seems you have some utf8 character in your result set
add this statement before running your query
mysql_query('SET CHARACTER SET utf8');
Update
"mysql"
to
"mysqli"
and add
mysqli_set_charset($variável_de _conexão, 'utf8');
below the connection variable

MySQL SELECT on Arabic Word returns 0 results on PHP but does on SQLBuddy/phpMyAdmin

Problem
I am getting 0 results when searching for an Arabic word in a MySQL database using the SELECT query with PHP.
However, the same exact query yields results in alternative clients, namely SQLBuddy and the likes. Everything is encoded in UTF-8.
Code
<?php
$host = "localhost";
$username = "hans_wehr_client";
// i know my security is a joke :)
$password = "hans_wehr";
$database = "hans_wehr";
$conn = new mysqli($host, $username, $password, $database);
if ($conn == TRUE){
$search = $_GET["search"];
$encoded_search = utf8_encode($search);
echo $encoded_search."<br>";
header('Content-Type: text/html; charset=utf-8');
$sql = "SELECT * FROM dictionary WHERE ARABIC LIKE '$search'";
echo $sql."<br>";
mysqli_query($conn,"SET NAMES 'utf8'");
mysqli_query($conn,'SET CHARACTER SET utf8');
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
header('Content-Type: text/html; charset=utf-8');
echo $row["ARABIC"]. " - Meaning: " . $row["ENGLISH1"]. " " . $row["ENGLISH2"]. "<br>";
}
}else {
echo "0 results";
}
}
?>
Before the mods get the pitchforks, I have to clear up my troubleshooting logic.
Encoding. I set the page encoding to utf-8 using header('Content-Type:
text/html; charset=utf-8'); and ran the queries mysqli_query($conn,"SET NAMES 'utf8'"); and mysqli_query($conn,'SET CHARACTER SET utf8');, this cleared up the ??????? and Ùؤتا
rendered instead of Arabic words issue. That is kind of a different
issue. Source. and Source2.
Database Charset. My database and columns are set to UTF-8.
Other clients work. SQLBuddy/MySQL native client/ PHPMyAdmin appear to be working because running the same exact query yields result. Therefore I appear to be on the same bloody boat with him. The query SELECT * FROM dictionary WHERE ARABIC LIKE 'آخَر، أُخرى' returns a result on SQLbuddy but nada on PHP.
Possible solution:
Running the query SELECT * FROM dictionary WHERE ARABIC LIKE 'آخَر، أُخرى' yields me a result.
However running the query with a UTF-8 encoded version of the Arabic word returns 0 results. SELECT * FROM dictionary WHERE ARABIC LIKE 'آخَر، أُخرى' I think this simulates PHP.
The UTF-8 Arabic word version is obtained by decoding the automatically URL encoded $[_GET] parameter i.e %26%231570%3B%26%231582%3B%26%231614%3B%26%231585%3B%26%231548%3B+%26%231571%3B%26%231615%3B%26%231582%3B%26%231585%3B%26%231609%3B
Could it be that the MySQLi actually queries the UTF-8 version instead of the actual Arabic word? Therefore finding no match since they are different?
If so how can I explicitly tell PHP not to URL encode my search term and therefore pass it as it is?
Since according to my tinfoil theory, http://localhost/hans_wehr/search_ar.php?search=آخَر، أُخرى would work but http://localhost/hans_wehr/search_ar.php?search=%26%231570%3B%26%231582%3B%26%231614%3B%26%231585%3B%26%231548%3B+%26%231571%3B%26%231615%3B%26%231582%3B%26%231585%3B%26%231609%3B
Inputs will be greatly appreciated.
Use html_entity_decode():
Use html_entity_decode() on your $_GET["search"] value
<?php
$host = "localhost";
$username = "hans_wehr_client";
// i know my security is a joke :)
$password = "hans_wehr";
$database = "hans_wehr";
$conn = new mysqli($host, $username, $password, $database);
if ($conn == TRUE){
$search = $_GET["search"];
$encoded_search =html_entity_decode($search, ENT_COMPAT, 'UTF-8');
echo $encoded_search."<br>";
header('Content-Type: text/html; charset=utf-8');
$sql = "SELECT * FROM dictionary WHERE ARABIC LIKE '$encoded_search'";
echo $sql."<br>";
mysqli_query($conn,"SET NAMES 'utf8'");
mysqli_query($conn,'SET CHARACTER SET utf8');
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
header('Content-Type: text/html; charset=utf-8');
echo $row["ARABIC"]. " - Meaning: " . $row["ENGLISH1"]. " " . $row["ENGLISH2"]. "<br>";
}
}else {
echo "0 results";
}
}
?>

SELECT statement doesn't work with utf-8 [duplicate]

This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 1 year ago.
I have a select statement which should select all data in the database which equals to a Arabic input, I've set database's collation to utf8_general_ci and tables column as them for sure. And at the file
$conn = mysqli_connect($mysql_host, $mysql_user, $mysql_password, $mysql_database);
mysqli_query($conn, "set names 'utf8'");
mysqli_query($conn, "SET character_set_results=utf8");
mb_http_output('UTF-8');
mb_internal_encoding('UTF-8');
mb_http_input('UTF-8');
mb_language('uni');
mb_regex_encoding('UTF-8');
ob_start('mb_output_handler');
mb_language('uni');
mb_internal_encoding('UTF-8');
mysqli_set_charset($conn, "utf8");
And the code of the search
$question = $_REQUEST['question'];
$table = $_REQUEST['subject'];
if(empty($question)) {
echo "Type a question!"; }
$qe = mysqli_escape_string($conn, $question);
$full = "SELECT * FROM $table WHERE question LIKE '%$qe%'";
$fullQ = mysqli_query($conn, $full);
if(!$fullQ) {
echo mysqli_error($conn);
}
echo "<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'>";
printf(nl2br("\n%u\n"), mysqli_num_rows($fullQ));
while($row = mysqli_fetch_assoc($fullQ)) {
printf(nl2br("\n%s\n"), $row['question']);
}
It works if I print all the data without using WHERE and it also prints the SQL syntax after it is sent from the first page to the second one right with the correct Arabic characters. But it always return 0 rows.
If your database saved in arabic then set up connection string to the following
$con1 = mysqli_connect($HOSTURL,$DBUSER,$DBPASSWORD,$DBNAME);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die('');
}
mysqli_query($con1,"SET NAMES utf8");
//else{echo "Connection Done";}
if your database is not encoded then you do not have to set utf8 in your connection string.

Characters corrupted when inserted in database

I have a PHP script that gets a XML, selects some data, and insert them in my database (MySQL). All my fields are utf8_bin. This XML is ISO-8859-1, and can't change this because is another site that sends it to me.
Example: the string "NG Contábil" is set "NG Contábil" in my db. This is my script:
<?php
header('Content-Type: text/html; charset=utf-8');
mysql_query("SET NAMES 'utf8'");
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_results=utf8');
include '/PagSeguroLibrary/PagSeguroLibrary.php';
include '/PagSeguroLibrary/domain/PagSeguroAccountCredentials.class.php';
include 'conexao.php';
include 'alias_array.php';
include 'retorna_cpf.php';
$conexao = ConectaBD::get_instance();
$conexao->conectar_pronto();
$conexao->BD_pronto();
//(...)
$xml = simplexml_load_file('arquivo.xml');
if($xml === null)
$xml = simplexml_load_string($resposta_transacao);
$status = $xml->status;
$nome = $xml->sender->name;
$email = $xml->sender->email;
$codigo = $xml->code;
$vetor = $xml->items->item;
$cpf = retorna_cpf($email);
foreach($vetor as $v)
{
$nome_produto = $v->description;
if($nome_produto != 'frete')
{
//Retorna o id do produto a partir da descrição
$result = mysql_query('SELECT id_product
FROM ps_product_lang
WHERE name = "'.$nome_produto.'"');
$array = Array();
while($row = mysql_fetch_alias_array($result))
{
foreach($row as $linha)
array_push($array, $linha);
}
mysql_query('INSERT INTO pagamento(Status, Nome, Email, CPF, idproduto, Codigo, Inscrito, id, Enviado, NomeProduto)
VALUES ("'.$status.'", "'.$nome.'", "'.$email.'", "'.$cpf.'", "'.$array[0].'", "'.$codigo.'", 0, null, 0, "'.$nome_produto.'")');
}
}
fclose($arquivo);
unlink('arquivo.xml');
?>
Thanks for any answer!
You have overlooked just one little nuance:
mysql_query("SET NAMES 'utf8'"); is not a magical spell that have to be cast in order to make proper encoding, but actually an SQL query, which needs to be run in the same instance you are actually using to run SQL queries.
So, if you are connecting to your mysql database using ConectaBD::get_instance(); you have to run SET NAMES utf8 query after that call, not before.
I don't know why, but adding utf8_decode() solves the problem
I know.
simplexml's output is always utf-8.
While, as I pointed out above, you don't set your client connection into utf8.
So, it remains default latin1
With (quite useless) utf8_decode() call you're casting your utf-8 data back into latin1 and thus it correctly stored into database.
This should solve your issue:
...
$xml = simplexml_load_file('arquivo.xml');
$xml = iconv('ISO-8859-1', 'UTF-8', $xml);
...

PHP+MYSQL encoding, utf8_polish_ci

Hello i have problem with encoding in my script.
My connect function looks like:
function connect()
{
$conn = mysql_connect('192.168.1.127', 'mason_frik', 'difficultpassword');
if (!$conn)
{
die('Nie można się połaczyć!');
}
mysql_query("SET NAMES 'utf8'; COLLATE='utf8_polish_ci';");
mysql_query("SET character_set_client = 'utf8'");
mysql_query("SET character_set_results = 'utf8'");
mysql_query("SET character_set_connection = 'utf8'");
mysql_select_db('mason_konkursy');
}
In my database i'm using utf8_polish_ci everywhere.
In my script i'm getting something from other page and i need to search it in my db like this:
//this function is parsing other page and get innertext of SPAN.
$question = GetSpanData($FirstQuestion, "dnn_ctr1975_ViewContestsContestNew_dc_question_lblQuestion");
$wyn = mysql_query('SELECT * FROM questions WHERE question="'.$question.'"');
$wynik = mysql_fetch_array($wyn, MYSQL_ASSOC);
Result is bool(false).
When i copy query to my phpmyadmin and paste to sql it is working, but from my script it didn't.
Can You help me?
This line is wrong:
mysql_query("SET NAMES 'utf8'; COLLATE='utf8_polish_ci';");
The correct syntax is:
SET NAMES 'charset_name' COLLATE 'collation_name'
In your case, the code would the be:
mysql_query("SET NAMES 'utf8' COLLATE 'utf8_polish_ci';");
And read the first comment posted by eggyal: mysql_* functions should not be used anymore, they are deprecated and will be removed from PHP in a future version.
You may be missing a call to mysql_real_escape_string in this line of code (it is not possible for me to be sure, it depends what the function GetSpanData exactly does):
mysql_query('SELECT * FROM questions WHERE question="'.$question.'"');
to escape the data properly, you must use the mysql_real_escape_string function:
mysql_query('SELECT * FROM questions WHERE question="'.mysql_real_escape_string($question).'"');

Categories