Swift Php Json Chinese Character - php

I have both English and Chinese Character in my database, but when I retrieve in JSON the Chinese Character does not work. Result is "?". Anyone can help me ?
<?php
header('Content-Type: text/html; charset=utf-8');
/* include db.config.php */
include_once("config.php");
// Get user id
$id = isset($_GET['username']) ? mysql_real_escape_string($_GET['username']) : “”;
if(empty($id)){
$data = array ("result" => 0, "message" => 'Wrong user id');
} else {
// get user data
$sql = mysql_query("SELECT username, gender, location, birthday, mobilephone, signature FROM users WHERE username='$id'");
$data = array ();
while ($row = mysql_fetch_array($sql, MYSQL_ASSOC)) {
$row_array['username'] = $row['username'];
$row_array['gender'] = $row['gender'];
$row_array['location'] = $row['location'];
$row_array['birthday'] = $row['birthday'];
$row_array['mobilephone'] = $row['mobilephone'];
$row_array['signature'] = $row['signature'];
//push the values in the array
array_push($data,$row_array);
}
echo json_encode($data);
mysql_close($conn);
/* JSON Response */
}
?>

Make sure your table fields collation are set to utf8-general-ci. Open your table -> Structure -> here check it. If it not, edit the field and change it. Now add new entry and check.

Related

How to pass special characters through php from a mssql database

I have this code is working fine my application gets the data with json and is all fine but when I insert special characters like ñ which I need to get I can't have been told that I should use the utf8_encode but I just don't know how to apply it here since.
<?php
require_once(dirname(__FILE__).'/ConnectionInfo.php');
//Set up our connection
$connectionInfo = new ConnectionInfo();
$connectionInfo->GetConnection();
if (!$connectionInfo->conn)
{
//Connection failed
echo 'No Connection';
}
else
{
if (isset($_POST['mod']) && isset($_POST['lec']) && isset($_POST['clase']))
{
$mod = $_POST['mod'];
$lec = $_POST['lec'];
$clase = $_POST['clase'];
//Create query to retrieve all contacts
$query = 'SELECT TituloEjercicio,PreguntaEjercicio,Opcion1Ejercicio,Opcion2Ejercicio,Opcion3Ejercicio,Opcion4Ejercicio,EstaCorrectaEjercicio FROM ejercicios WHERE QueModulo = ? and QueLeccion = ? and Queclase = ?';
$params = array($mod,$lec,$clase);
$stmt = sqlsrv_query($connectionInfo->conn, $query,$params);
if (!$stmt)
{
//Query failed
echo 'Query failed';
}
else
{
$contacts = array(); //Create an array to hold all of the contacts
//Query successful, begin putting each contact into an array of contacts
while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC)) //While there are still contacts
{
//Create an associative array to hold the current contact
//the names must match exactly the property names in the contact class in our C# code.
$contact = array("lbl_variable_cuestionario_titulo" => $row['TituloEjercicio'],
"lbl_variable_pregunta" => $row['PreguntaEjercicio'],
"opcion1" => $row['Opcion1Ejercicio'],
"opcion2" => $row['Opcion2Ejercicio'],
"opcion3" => $row['Opcion3Ejercicio'],
"opcion4" => $row['Opcion4Ejercicio'],
"EstaCorrecta" => $row['EstaCorrectaEjercicio']
);
//Add the contact to the contacts array
array_push($contacts, $contact);
}
//Echo out the contacts array in JSON format
echo json_encode($contacts);
sqlsrv_close($connectionInfo->conn);
}
}
sqlsrv_close($connectionInfo->conn);
}
sqlsrv_close($connectionInfo->conn);
?>
If your issue lies with pushing non-latin characters to MySQL then you might just have to configure your database to use UTF8. There are good tutorials online that show you how to do that.

How to display special character in json using php

I am creating web service for android which in php.
In database, there are some rows where it contains html and css define.
While fetching data from database json shows null data.
Any Help will be helpful
Example
Vivenda dos Palhaços this shows me result "null"
My code:
<?php
error_reporting(~E_ALL);
$format = $_REQUEST['format'];
if(!isset($format))
$format = "json";
if($format == 'json') {
header('Content-Type: application/json');
} else if ($format == 'xml') {
ob_clean();
header('Content-Type: text/xml; charset=ISO-8859-1');
echo "<?xml version='1.0' encoding='ISO-8859-1'?>";
}
//open database connection
include 'config.php';
include 'open_db_connection.php';
include 'util.php';
mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET COLLATION_CONNECTION = 'utf8_unicode_ci'");
$region = $_REQUEST['region'];
$method = $_REQUEST['method'];
if($method == 'GET') {
if($region == 'Central')
{
$q=$_REQUEST['q'];
$famille_id = $_REQUEST['famille_id'];
//print $famille_id; exit;
$sql_fn = "SELECT * FROM region WHERE id='4'"; //Central Goa
$result2 = mysql_query($sql_fn) or die(mysql_error());
$row2 = mysql_fetch_assoc($result2);
$sql = "select id,titre,famille_id from categorie where famille_id =".$famille_id;
$result = mysql_query($sql, $db) or die(mysql_error());
$j=0;
while ($row = mysql_fetch_assoc($result))
{
$sql="SELECT * FROM etablissement where categories LIKE '%".$row['id']."%' AND familles LIKE '%".$row['famille_id']."%' AND region_id LIKE '%".$row2['id']."%'";
$result1 = mysql_query($sql,$db) or die(mysql_error());
$i=0;
while($row3 = mysql_fetch_assoc($result1))
{
$arraycont[$i]['main_category_name'] = 'PARTY';
$arraycont[$i]['categories_name'] = $row['titre'];
$arraycont[$i]['categories'] = $row['id'];
$arraycont[$i]['sstitre'] = $row3['sstitre'];
$arraycont[$i]['adresse'] = $row3['adresse'];
$arraycont[$i]['lieu'] = $row3['lieu']." / ".$row2['nom']." | ".$row['titre'];
$arraycont[$i]['nom'] = $row3['nom'];
$arraycont[$i]['txtintro'] = $row3['txtintro'];
$arraycont[$i]['image'] = $imagepath.$row3['id']."/01.jpg";
$arraycont[$i]['latitude'] = $row3['latitude'];
$arraycont[$i]['longitude'] = $row3['longitude'];
$arraycont[$i]['txtcontact'] = $row3['txtcontact'];
$arraycont[$i]['tel'] = $row3['tel'];
$i++;
}
$finalarray[$j]["titre"] = $row['titre'];
$finalarray[$j]["id"] = $row['id'];
$finalarray[$j]["categories"] = $arraycont;
$j++;
}
echo json_encode($finalarray); // final output in JSON
}
include 'close_db_connection.php';
?>
First of all You must need to set the database table collation to UTF-8 general ci.
then before fetch the data by select query you need to insert these char set lines.
mysql_query("SET NAMES 'UTF8'");
request_result = executre your select query.
I don't know what your DB encoding is, but I assume it's ISO-8859-1, because you also output your page in this encoding.
The problem is, that JSON is, by definition, always UTF-8 encoded. Also, PHP's json_encode doesn't accept input in other encodings than UTF-8; if it encounters characters in a different encoding anywhere in your object strucure, the respecive node will be null.
The following example will demonstrate this effect:
$test = array('foo' => 'äöü', 'bar' => 'äöü');
$test['foo'] = mb_convert_encoding($test['foo'], 'ISO-8859-1', 'UTF-8');
echo json_encode($test);
Result:
{"foo":null,"bar":"\u00e4\u00f6\u00fc"}
Solution: Convert your DB output to UTF-8, save your HTML files in UTF-8, and set your Headers to UTF-8.
Your data has to be encoded as UTF-8 or ISO-8859-1.
http://www.php.net/manual/de/function.json-encode.php
Because if you try to convert an array of non-utf8 characters you'll be getting 0 as return value

Unable to get data in proper format

I am unable to parse data in PHP from MySQL.
Here's my code
<?php
header('Content-Type: text/html; charset=utf-8');
// array for JSON response
$response = array();
echo 'भगवान';
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$result = mysql_query("SELECT *FROM create_event") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["create_event"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["id"] = $row["id"];
$product["desc"] = $row["desc"];
$text;
array_push($response["create_event"], $product);
}
// success
$response["success"] = 1;
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
?>
It's my database, I have set all the collation in utf-8 ci format but still not working:
I have tried all possible solutions and help online and have gone through popular posts and answers and also have set browsers settings to support Hindi lang but still displaying ? marks in output. Here is the output format
भगवान{"id":"1","desc":"???? ??????"}
mysql_query('SET character_set_results=utf8');
Use this after connecting to database or before using any select statement.

testing php function with poster extention

I made a simple API to get the data from the database to be viewd at android app
I have a Problem testing my php functions
example of the functions:-
<?php
include 'json_config.php';
function get_city(){
mysql_query("SET NAMES utf8;");
mysql_query("SET CHARACTER_SET utf8;");
$return=array();
//$country_name=$_POST['country_name'];
// get all products from products table
$result = mysql_query("SELECT *FROM city") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["city"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
// Full texts id dead_name masged_name gender salah notes date city_name hour min
$region_subscribt = array();
$region_subscribt["id"] = $row["id"];
$region_subscribt["city_name"] = $row["city_name"];
$region_subscribt["region_name"] = $row["notes"];
$region_subscribt["notes"] = $row["country_name"];
// push single product into final response array
array_push($response["city"], $region_subscribt);
}
// echoing JSON response
echo json_encode($response,JSON_UNESCAPED_UNICODE);
} else {
// no products found
$response["fail"] = 0;
// echo no users JSON
echo json_encode($response,JSON_UNESCAPED_UNICODE);
}
}//end of the function
// get_city();
?>
when I using poster extention with firefox and put at the content , I got no data
when I put at the content
getcity();
but when I call the function inside the php file I got the data correctly !
How to pass the values at the httprequest to use the returned json at another app !
You need to send the method name as a parameter not as a content and then check the method name and call the code you need.
see this snapshot
if(isset($_GET['method_name']) && $_GET['method_name']) == 'get_city') {
get_city();
}
you also need to set the content type as following
header('Content-type: application/json');
your final code will be something like this
<?php
include 'json_config.php';
function get_city(){
mysql_query("SET NAMES utf8;");
mysql_query("SET CHARACTER_SET utf8;");
$return=array();
//$country_name=$_POST['country_name'];
// get all products from products table
$result = mysql_query("SELECT *FROM city") or die(mysql_error());
header('Content-type: application/json');
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["city"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
// Full texts id dead_name masged_name gender salah notes date city_name hour min
$region_subscribt = array();
$region_subscribt["id"] = $row["id"];
$region_subscribt["city_name"] = $row["city_name"];
$region_subscribt["region_name"] = $row["notes"];
$region_subscribt["notes"] = $row["country_name"];
// push single product into final response array
array_push($response["city"], $region_subscribt);
}
// echoing JSON response
echo json_encode($response,JSON_UNESCAPED_UNICODE);
} else {
// no products found
$response["fail"] = 0;
// echo no users JSON
echo json_encode($response,JSON_UNESCAPED_UNICODE);
}
}//end of the function
if(isset($_GET['method_name']) && $_GET['method_name']) == 'get_city') {
get_city(); }
?>
and here is some very good and pretty easy tutorial summarize the whole precess
Create a Basic Web Service Using PHP, MySQL, XML, and JSON

I'm trying to retrieve data from mysql using php for my Flex Mobile application, but no luck

I am creating a login based application and this is what I have so far. I am trying to read each field into a separate textarea. I have tried to bind the data etc. I do get a output in the textarea, but it prints all the fields in one textarea. Please help.
<?php
selectDB();
function selectDB() {
$usertoken = $_POST['usertoken'];
//Database service vars
$databasehost = "localhost";
$databasename = "morerandom";
$databasetable = "random";
$databaseusername = "root";
$databasepassword = "root";
$con = mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
$query = "SELECT username, useremail, firstname, lastname FROM $databasetable WHERE usertoken='$usertoken'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if ($count)
{
$rows = array();
while ($row = mysql_fetch_object($result)) {
$rows[] = $row;
}
echo $rows[0]->username . "\n";
echo "\n";
echo $rows[0]->useremail . "\n";
echo $rows[0]->firstname . "\n";
$first = $rows[0]->lastname;
echo $first;
// echo "$lastname;"
}
else
{
echo 'Token not valid';
}
mysql_free_result($result);
mysql_close($con);
}
?>
What you are getting is just one string. There are better way to retrieve this kind of data from the server side(XML or AMF).
If you want to go ahead with your method then split the string using '\n' as a delimiter but check first that the server response is not 'Token not valid'.
So something like this should work:
First remove the echo "\n"; line under the echo $rows[0]->username . "\n";
var responseArray:Array = theStringResult.split('\n');
So now the responseArray stores the username at position 0, useremail at position 1, firstname at position 2 and lastname at position 3.
But again, you are sending data from the server as raw text and this is not the best way to do it. Check this link to see how this can be done using AMFPHP.

Categories