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
Related
I am pulling data from the database with the sql command. But I take trouble when shooting Turkish characters. For example, I have this problem when there are characters like "ü, ç, ğ, ş". How can I retrieve Turkish characters from the database without problems? I'm running this sql command in the React native.
<?php
....
$sql = "SELECT ADET FROM ....TBL_STT_SIPARISLER";
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "No Results Found.";
}
echo $json;
$conn->close();
?>
JSON must be encoded in UTF-8.
You can set the charset of your connection with the function $conn->set_charset('utf8')
I have a database connection that I have made with a odbc connector. The problem is that I have a field that has special characters, such as accents, and it does not recognize them.
This is my webservice:
<?php
define('CHARSET','UTF-8');
header('Content-Type: text/html; charset=UTF-8');
$usuario='';
$pass='';
$dsn='Tr3';
$conexion = odbc_connect($dsn,$usuario,$pass);
$sql="select total, name, domin from F_VENTA where Ve_FirmaCamion=true";
$rs = odbc_exec($conexion, $sql);
if (!$rs) {
exit("Error al conectar la base de datos");
}
$datos = array();
$i = 1;
while($row = odbc_fetch_array($rs)) {
$datos[] = $row;
$i++;
}
odbc_close($conexion);
$json = json_encode($datos);
echo $json;
?>
This works perfectly. But if the field "name" has some special character (accents, ñ, Ç ...) then the webservice does not return anything to me. The json leaves me blank.
I tried with:
utf8_decode($json);
and
$cadena= htmlentities($json, ENT_QUOTES, "UTF-8");
but don't work.
Any advice? Thanks!
I bring my solution to the problem in case it happens to someone else.
I have managed to solve if before coding the data to json, I pass the mb_convert_encoding() method to the data that comes to us from the database while it traverses it. So I'll encode them in the while loop:
while($row = odbc_fetch_array($rs)) {
$datos[] = mb_convert_encoding($row, "UTF-8", "iso-8859-1");
$i++;
}
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.
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.
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