Connection ODBC with special characters - php

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++;
}

Related

json parse error unexpected eof turkish character

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')

Json return null

I have the next problem doing a json to read in Andorid
(the credentials are hidden but connection going good in others files)
class reportes
{
var $parametro;
var $conexion;
function __construct(){
$host = "IP"; $DBName = "DbName";
$usuario="user"; $contrasena="pass";
$driver = "DRIVER={iSeries Access ODBC Driver};
SYSTEM=$host;Uid=$usuario;
Pwd=$contrasena;Client_CSet=UTF-8;";
$this->conexion = odbc_connect($driver, $usuario, $contrasena);
}
function consulta($parametro){
$query=
"SELECT OHSNME,OHTOT$,OHREPÑ
FROM MYDB.SANFPRD.FOMHDR
WHERE OHORDÑ= $parametro ";
echo $query."<br><br>";
if ($this->conexion == 0) {echo "Ha fallado la conexion a la BBDD </br>";}
else{
$datos = array();
$result=odbc_exec($this->conexion,$query);
while($row = odbc_fetch_object($result)){
$datos[]= $row;
}
echo json_encode($datos);
}
}//Fin funcion consulta()
}//Fin de la clase
$consultar = new reportes();
$nota_venta = $_REQUEST['parametro'];
$consultar->consulta($nota_venta);
the response JSON that i get is:
SELECT OHSNME,OHTOT$,OHREPÑ FROM DELLORTO.SANFPRD.FOMHDR WHERE OHORDÑ= 366
[{"OHSNME":"E.C. GM. ","OHTOT$":"1861.00",null:" A07"}]
you can see that OHORDÑ is probably the problem with the 'Ñ'
but this table are part a productive database and i can't update
Solution #1, alias the column name to a name without non-ascii characters:
$query=
"SELECT OHSNME,OHTOT$,OHREPÑ AS OHREPN
FROM MYDB.SANFPRD.FOMHDR
WHERE OHORDÑ= $parametro ";
Solution #2, manually serialize using utf8_encode():
$result=odbc_exec($this->conexion,$query);
while($row = odbc_fetch_object($result)){
$_row_fix = array();
foreach ($row as $field => $val) {
$_row_fix[utf8_encode($field)] = utf8_encode($val);
}
$datos[]= $_row_fix;
}

JSON ["data","pre database"]

So, I put my php page to connect to my android app on a hosted server (Hostgator). Now my PHP script for the JSON data seems to not be returning properly.This was working on my wamp server just fine. Example below of issue...
["data","pre database"][{"email":"thomas#wiregrass.edu","password":"test","fname":"Thomas","lname":"Cummings","phone":"5052030822","temppass":"15151","alert":"B"}]
Any ides as to what I did wrong or what is going on would be appreciated.
PHP script (might be outdated, this project is old):
<?php
$user = "ab73953_test";
$pass = "H3#ther78";
$db = "ab73953_testdb";
$out = array('data', 'pre database');
echo json_encode($out);
$db = mysqli_connect('localhost', $user, $pass, $db) or die("did not work");
$email=$_POST['username'];
$email = "thomas#wiregrass.edu"; // testing
$qry = 'SELECT * FROM users WHERE email = "'. $email .'"' ;
$result = mysqli_query($db, $qry) or die(" did not query");
$count = mysqli_num_rows($result);
$output = array();
if($count > 0){
while($row = mysqli_fetch_assoc($result))
{
$output[]=$row;
}
echo json_encode($output);
}
else
echo json_encode("Could not find user");
mysqli_close($db);
?>
That's not valid JSON. JSON is basically javascript: If the json you generate would be a javascript syntax error, then it's not valid json.
You have two separate echo json_encode(...) blocks, so you're producing two entirely separate/distinct json strings. Your output can only be one SINGLE json string.
e.g. [...][...] is two separate arrays that have gotten glued together. It's a javascript syntax error, therefore it's also invalid json. If you had something like
$arr1 = array(...);
$arr2 = array(...);
echo json_encode(array($arr1, $arr2));
you'd end up with
[[...],[...]]
and be ok
But you have
echo json_encode($arr1);
echo json_encode($arr2);
and end up with
[...][...]
which is an outright syntax error.
And note that you're vulnerable to sql injection attacks.

output json with database

Sorry for my English. I'm trying to output the data to a database format json. It seems to do everything right, but it is not true outputs. Here is my link which is obtained: http://ksupulse.tk/get_all.php if I did check the validity of the site http://jsonlint.com/ or http://jsonformatter.curiousconcept.com/ get an error.
get_all.php
<?php
header('Content-Type: application/json; charset=utf-8');
?>
<?php
$response = array();
require 'db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query("SELECT * FROM demo") or die(mysql_error());
if (mysql_num_rows($result) > 0) {
$response["demo"] = array();
while ($row = mysql_fetch_array($result)) {
$product = array();
$product["id"] = $row["id"];
$product["name"] = $row["name"];
$product["detaly"] = $row["detaly"];
array_push($response["demo"], $product);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No products found";
echo json_encode($response);
}
?>
I've honestly spent so much time searching for this problem, but the answer is not found. All the same, why do I have prints to the database is not json? DB encoded utf_unicode_ci, and the table in utf8_general_ci
There is an extraneous carriage return in front of your { } sequence (which is valid, in itself).
You should not close ?> and then reopen <?php your script after the header instruction.
It outputs garbage to the browser. You really want your stream to begin with the { first character.
In other words (for #KnightRider) the lines 5-7 of the script should be removed!
05 ?>
06
07 <?php
Sorry for answering this is because I could not attempt but have to write my views
Hi, I have checked this which you posted in the comment and JSONlint verifies it as a valid JSON
{"demo":[{"id":"3","name":"123123","detaly":"123123123"},{"id":"4","name":"4444‌​‌​","detaly":"555555"}],"success":1}
What else do you need?

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

Categories