PHP UTF-8 Encoding is messing up - php

I'm outputting some multi-lingual data from my database into a JSON object, but the output isn't showing foreign characters, it just shows question marks even though I have the header charset set to utf8 as such:
header('Content-Type: application/json; charset=utf-8');
When I look at the data in phpMyAdmin, it shows the characters correctly. Is there something I'm doing wrong?
Here is the PHP code that is formatting the JSON output:
$numRows = new stdClass();
$mysqli = dbiConnect();
$query = "SELECT * FROM country_codes";
if ($stmt = $mysqli->prepare($query)) {
/* execute query */
$stmt->execute();
/* store result */
$stmt->store_result();
$numRows->cc = $stmt->num_rows;
/* close statement */
$stmt->close();
}
$mysqli->close();
$count = 0;
$dataCountryCodes = '{';
$mysqli = dbiConnect();
$query = "SELECT * FROM country_codes";
if ($result = $mysqli->query($query)) {
while($row = $result->fetch_assoc()){
$count++;
$rowData = new stdClass();
$rowData->code = $row['code'];
$rowData->name = $row['name'];
$dataCountryCodes = $dataCountryCodes.'"'.$rowData->code.'": {"Code":"'.$rowData->code.'","Country":"'.$rowData->name.'"}';
if ($count != $numRows->cc) {
$dataCountryCodes = $dataCountryCodes.',';
}
}
}
$mysqli->close();
$dataCountryCodes = $dataCountryCodes.'}';
if ($returnCountryCodes == 1) {
return $dataCountryCodes;
} else {
header('Content-Type: application/json; charset=utf-8');
echo ($dataCountryCodes);
}
This is what I am getting:
{"AE": {"Code":"AE","Country":"United Arab Emirates (???????? ???????? ????????)"}}
This is what I got when it was hand coded, this would render fine after I translated the JSON to HTML:
{"AE": {"Code":"AE","Country":"United Arab Emirates (الإمارات العربيّة المتّحدة)"}}

You didn't show dbiConnect function. Check it and try using SET NAMES 'UTF8' after connecting to MySQL:
$con=mysqli_connect("host", "user", "pw", "db");
if (!$con)
{
die('Failed to connect to mySQL: ' .mysqli_connect_errno());
}
/* change character set to utf8 */
if (!$con->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $con->error);
}
As the manual says:
SET NAMES indicates what character set the client will use to send SQL
statements to the server... It also specifies the character set that the server should
use for sending results back to the client.

try this:
$mysqli = dbiConnect();
$mysqli->query("set names utf8")

Related

PHP foreach loop return null vaule [duplicate]

This question already has answers here:
How to convert mysqli result to JSON? [duplicate]
(6 answers)
Closed 3 years ago.
I want to fetch my sql data to json
It work when I try in xampp
but when I load to server It return null value
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
printf("Initial character set: %s\n", $mysqli->character_set_name());
/* change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $mysqli->error);
exit();
} else {
printf("Current character set: %s\n", $mysqli->character_set_name());
}
//query to get data from the table
$query = sprintf("SELECT playerid, score FROM score ORDER BY playerid");
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data);
And this is result when I run
Initial character set: latin1
Current character set: utf8
[null,null,null,null,null]
this is my sql data
How to fix it.
I search I try but not work.
MySQLi requires you to fetch the data first, you can't loop the query object. Get rid of your foreach loop and use
while ($row = $result->fetch_assoc()) {
data[] = $row;
}
http://php.net/manual/en/mysqli-result.fetch-assoc.php
Try this logic
while ($row = $result->fetch_row()) {
$data[] = $row;
}

php json_encode returns blank for array

I am trying to return the result of a mysql query as json, but the json_encode function always returns a blank although the array contains elements.
Here is the relevant code
Retrieve the query and convert to php array:
$sql = "blablabla";
$clients = mysql_query($sql, $con);
$result = array();
while($row = mysql_fetch_assoc($clients)) {
//echo "rij: " . $row['name'];
$result[] = $row;
}
Then I return the result:
echo json_encode($result);
This returns nothing, while I do get results when echoing the following statements:
echo count($return);
returns 1
echo $return[0];
returns "Array"
echo $return[0]['name'];
returns "YOUREKA! demo"
Any idea what I am doing wrong?
Edit: I have one record that is and should be returned which contains following data:
id: 2,
name: YOUREKA! demo,
address: Italiëlei 26,
postalcode: 2000,
city: Antwerpen,
country: België,
countrycode: BE,
telephone: +32-476061346,
email: mats#youreka.be,
distance: 30.762980999827132,
The documentation on json_encode() states "All string data must be UTF-8 encoded. ". Your attempts to use mysql_set_charset is the right kind of thinking.
Use this kind of debuggery:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
printf("Initial character set: %s\n", $mysqli->character_set_name());
/* change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $mysqli->error);
exit();
} else {
printf("Current character set: %s\n", $mysqli->character_set_name());
}
$mysqli->close();
?>
I write a demo of php/mysql connection, with json data: Working fine
<?php
// we connect to localhost
$link = mysql_connect('localhost', 'username', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db("db_name")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$query = 'SELECT * FROM users where id = 1';
//Query database
$result = mysql_query ($query);
$arr = array();
//Iterate result
while ($record = mysql_fetch_assoc ($result)){
$arr[] = $record;
// print_r ($record);
}
echo "<pre>".print_r($arr,1)."</pre>";
echo json_encode($arr);
mysql_close($link);
?>
Note : This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0

PHP JSON result multiple empty

I developed an android application with Mysql database. I would like the result of my sql query is displayed in a JSON variable in a table. If I use a single column of my TableA "country" ---> "id_country" or "name_en_country" it works but if I want to display more columns ---> "id_country" AND "name_en_country" AND more .. ... The result Requet php send me a blank page. Could you help me please thank you!
<?php
// Create Database connection
$mysqli = new mysqli("localhost", "root", "", "whenmeeat");
if (!$mysqli) {
printf("Échec de la connexion : %s\n", mysqli_connect_error());
}
// Replace * in the query with the column names.
$result = $mysqli->query("select id_country, name_en_country, name_fr_country from country", MYSQLI_USE_RESULT);
// Create an array
$json_response["country"] = array();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$row_array['id_country'] = $row['id_country'];
$row_array['name_en_country'] = $row['name_en_country'];
// push the values in the array
array_push($json_response["country"],$row_array);
}
echo json_encode($json_response["country"]);
// Close the database connection
$mysqli->close();
?>
Based on the example set here json_encode() array in while loop for mySQL for calendar your code should alter like this:
<?php
// Create Database connection
$mysqli = new mysqli("localhost", "root", "", "whenmeeat");
if (!$mysqli) {
printf("Échec de la connexion : %s\n", mysqli_connect_error());
}
// Replace * in the query with the column names.
$stmt = $mysqli->prepare("SELECT `id_country`, `name_en_country`, `name_fr_country` FROM `country`");
$stmt->execute();
$res = $stmt->get_result();
// Create an array
$json = array();
while ($row = $res->fetch_assoc()) {
$country = array(
'id_country' => $row['id_country'],
'name_en_country' => $row['name_en_country'],
'name_fr_country' => $row['name_fr_country']
);
$json[] = $country ;
}
echo json_encode($json);
// Close the database connection
$mysqli->close();
?>

Php script query on mysql

So I used php to connect my android app to a mysql database. I tested both the app and the queries on several small databases. Everything worked fine.
Using the old query on a larger database made the php query load forever in the web browser thus not displaying the intended JSON. So I made a new query but it doesn't display any result in the app, plus, it only displays the last result on the query. Is there any way for this to work out correctly?
Old php query that works on small db, but loads forever in the web browser with larger db:
<?php
error_reporting(0);
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query("SELECT eid,marca,investimento,marcatotal,dataconstituicao,datainicio FROM empresa") or die(mysql_error());
header('content-type: application/json; charset=utf-8');
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_results=utf8');
if (mysql_num_rows($result) > 0) {
$response["empresa"] = array();
while ($row = mysql_fetch_array($result)) {
$product = array();
$product["eid"] = $row["eid"];
$product["marca"] = $row["marca"];
$product["investimento"] = $row["investimento"];
$product["dataconstituicao"] = $row["dataconstituicao"];
$product["datainicio"] = $row["datainicio"];
array_push($response["empresa"], $product);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No empresa found";
echo json_encode($response);
}
?>
New php query that I created that displays ONLY the last result in web browser and doesn't show anything in the app on new larger db:
<?php
//error_reporting(E_ALL);
error_reporting(0);
require_once('db_config.php');
$conn = mysql_connect($db_server, $db_user, $db_password) or die(mysql_error());
$db= mysql_select_db($db_database, $conn);
$sql="SELECT eid,marca,investimento,marcatotal,dataconstituicao,datainicio FROM empresa" ;
header('content-type: application/json; charset=utf-8');
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_results=utf8');
$rs = mysql_query($sql,$conn);
while ($row=mysql_fetch_assoc($rs))
{
$i=0;
foreach($row as $key => $value)
{
if (is_string($key))
{
$fields[mysql_field_name($rs,$i++)] = $value;
}
}
$json_result ["empresa"] = $fields;
}
$response = json_encode($json_result);
print_r($response);
?>
The aswer from Patrick Q is correct:
$json_result ["empresa"] had to be $json_result ["empresa"][] = $fields;
Also, his suggestion helped me solve my problem further since I just removed the success=1 logic alltogether from my app in order for it to work. Thank you all for the help!

MySql UTF8 collation data with accents not displayed properly when PHP fetched

I am fetching some data having UTF8 collation (utf8_unicode_ci) from a MySQL database with PHP. I am using this piece of code:
function advancedDatabaseSearch($pattern, $lpref) {
$link = mysql_connect(DB_URL, DB_USER, DB_PWD);
if (!$link) {
return 'Could not connect: ' . mysql_error();
}
$esc_value = mysql_real_escape_string($pattern);
$esc_lpref = mysql_real_escape_string($lpref);
mysql_select_db(DB_NAME, $link);
$query = "SELECT RAWVALUE FROM rawvalueitem "
."WHERE RAWVALUE LIKE '".$esc_value."' "
."AND LANGUAGE = '".$esc_lpref."' "
."ORDER BY RAWVALUE ASC";
$result = mysql_query($query);
$return = "";
while($row = mysql_fetch_array($result)) {
$return = $return.$row['RAWVALUE']." ";
}
mysql_close($link);
return $return;
}
and then from the php called by Ajax:
$result = advancedDatabaseSearch($tttmp, $lpref);
echo $result;
return;
Yet, when I display the result in a text area, the accents are not displayed properly:
On the other side, when I fetch UT8 data from a file:
if ( $file_loc != NULL ) {
if ( file_exists($file_loc) ) {
$handle = fopen($file_loc, "rb");
$contents = fread($handle, filesize($file_loc));
fclose($handle);
$result = $contents;
}
}
echo $result;
return;
I don't get this issue !!! How can I solve it when using PHP to fetch data from MySql?
Did you set UTF-8 as the default character set of your database connection?
mysql_set_charset('utf8', $link);
http://www.php.net/manual/en/function.mysql-set-charset.php
Also, does your page have a <meta> tag with the correct character set?
This is working like a.. you now!
<?php
$config_db_server='localhost';
$config_db_server_username='root';
$config_db_server_password='';
$config_db_database='test';
$config_db_charset='utf8';
$config_db_collation='utf8_general_ci';
$config_table_prefix='class_';
$config_live_site='http://localhost';
$config_abs_path='C:\xampp\htdocs';
$config_debug=0;
$dbLink = mysql_connect($config_db_server, $config_db_server_username, $config_db_server_password);
mysql_query("SET character_set_results=utf8", $dbLink);
mb_internal_encoding('utf8');
mysql_query("set names 'utf8'",$dbLink);
?>
Change here your db connect: ( $dbLink = mysql_connect($config_db_server, $config_db_server_username, $config_db_server_password); )

Categories