passing special characters from mysqli database to android app using php - java

I have a mysqli table on a server with the configuration displayed below. The text data contains some special characters. I'm passing this to my android app using the following php file. The issue is that all the special characters are displayed as question marks in the app. I'm not sure if I need to specify that we're passing unicode characters in the php file and if so how to do that. It's not a font issue, as any special characters hardcoded into the app display as expected.
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connectmaths.php';
// connecting to db
$con = new DB_CONNECT();
$con->connect();
// get all gamelists from gamelists table
$result = mysqli_query($con->myconn, "SELECT * FROM `abcd`" ) or die(mysql_error());
// check for empty result
if (mysqli_num_rows($result) > 0) {
// looping through all results
// gamelists node
$response["gamelist"] = array();
while ($row = mysqli_fetch_array($result)) {
// temp user array
$gamelist = array();
$gamelist["id"] = $row["id"];
$gamelist["zadanie"] = $row["zadanie"];
$gamelist["odp_a"] = $row["odp_a"];
$gamelist["odp_b"] = $row["odp_b"];
$gamelist["odp_c"] = $row["odp_c"];
$gamelist["odp_d"] = $row["odp_d"];
$gamelist["comment"] = $row["comment"];
$gamelist["correctanswer"] = $row["correctanswer"];
// push single gamelist into final response array
array_push($response["gamelist"], $gamelist);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no gamelists found
$response["success"] = 0;
$response["message"] = "No gamelists found";
// echo no users JSON
echo json_encode($response);
}
?>

What's Charset yours Datas ? When my Datas have e.g. charset cp1250 i have to transfer Strings to utf8. Change PHP script
...
while ($row = mysqli_fetch_array($result)) {
// temp user array
$gamelist = array();
$gamelist["id"] = $row["id"];
//$gamelist["zadanie"] = $row["zadanie"];
$gamelist["zadanie"] = iconv("CP1250", "UTF-8", $row["zadanie"]);
$gamelist["odp_a"] = $row["odp_a"];
$gamelist["odp_b"] = $row["odp_b"];
$gamelist["odp_c"] = $row["odp_c"];
$gamelist["odp_d"] = $row["odp_d"];
$gamelist["comment"] = $row["comment"];
$gamelist["correctanswer"] = $row["correctanswer"];
// push single gamelist into final response array
array_push($response["gamelist"], $gamelist);
}
...
The same before i save Datas from App to Mysql i have to transfer
...
$zadanie = iconv("UTF-8", "CP1250", $_POST['zadanie']);
...

Related

Class still pass the old array in PHP

I have an android program that passes 2 value to mySQL, that is Time in and Time out. I don`t know what happen but I have a scenario that the data passed is incomplete. For example i will create a record and the only need to put is time in after i type the time i will click save so the record is time in has a data and time out is null. After saving, my auto passer sends that data to mySQL. The next thing I will do is to edit that record to add Time Out so both of them has a data. auto passer will run after checking to my database my both of columns has a data. Now this is where the error begins, I have a button call refresh which will retrieve my data from mySQL,create a JSON of that then send it in my android after the process the returned data has no Time Out and when i check it the data in mySQL has no time out also even i add it. I dont know what happened
What I did in my Java is to create a JSONArray the convert it to string the pass it in my php file then my php file decodes it then loop it while saving to database.
This is how i create a json
JSONArray vis_array = new JSONArray();
Cursor unsync_vis = Sync.Unsync_Visit_All();
while (unsync_vis.moveToNext()) {
JSONObject vis_data = new JSONObject();
try {
vis_data.put("t1", formatInsert_n(unsync_vis.getString(unsync_vis.getColumnIndex("t1"))));
vis_data.put("t2", formatInsert_n(unsync_vis.getString(unsync_vis.getColumnIndex("t2"))));
vis_array.put(vis_data);
} catch (JSONException e) {
e.printStackTrace();
Log.e("Auto Sync Error", e.getMessage());
}
}
public String formatInsert_n(String data) {
if (TextUtils.isEmpty(data) || data.length() == 0) {
data = "null";
} else {
data = data.replace("'", "''");
data = data.replace("null", "");
if (data.toString().matches("")) {
data = "null";
} else {
data = "'" + data + "'";
}
}
return data;
}
after creating that json, i will convert it to string the pass it using stringRequest then in my php i will decode it use for loop the save it in mySQL
Here is the php code
<?php
header('Content-Type: application/json');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$insert_visit_new = isset($_POST['insert_visit_new']) ? $_POST['insert_visit_new'] : "";
if ($insert_visit_new != "") {
$vis_array = json_decode($insert_visit_new, true);
$vis_count = count($vis_array);
for ($i = 0; $i < $vis_count; $i++) {
$vis = $vis_array[$i];
$t1 = $vis['t1'];
$t2 = $vis['t2'];
$ins_sql = "INSERT INTO table t1,t2 VALUES ('$t1','$t2') ON DUPLICATE KEY UPDATE t1 = $t1,t2 = $t2"
$stmt = $DB->prepare($ins_sql);
$stmt->execute();
}
}
echo "done";
?>
by the way the code above is inside an AsyncTask and the class is a BroadcastReceiver
is the cause is i dont unregister my BroadcastReceiver?
or my jsonArray name from this class and inside my refresh button are same?
my question is whats wrong? looks like it still passes the old data. any help is appreciated TYSM

How to store List of adb devices on network into php array

Running the command:
$output = shell_exec("adb devices -l");
echo "$output";
and getting output like this:
List of devices attached
10.16.21.138:5555 device product:tbltevzw model:SM_N915V device:tbltevzw
10.16.20.90:5555 device product:ghost_verizon model:XT1060 device:ghost
can some one help to store this information into php associative array?
// remove extra spaces, then split into array by new lines
$arr = explode("\n", preg_replace('/ +/',' ',$x));
array_shift($arr); // remove 1-st line
$result = Array();
foreach($arr as $v)
{
$tmp = explode(' ',$v); // split each line into words
list($ip,$port) = explode(':',$tmp[0]);
$item = Array('ip'=>$ip, 'port'=>$port);
array_shift($tmp); // remove IP:PORT
array_shift($tmp); // remove DEVICE
foreach($tmp as $n)
{
list($key,$data) = explode(':',$n); // split by :
$item[$key] = $data; // accumulate key/data pairs
}
$result[] = $item; // append device to the result array
}

getJSONObject with an Array

i am trying to work with android and php json , i try to get something like this , how it is shown in an example.
the example json respone is: { "android": [ { "ver": "1.5", "name": "Cupcake", "api": "API level 3" }, { "ver": "1.6", "name": "Donut", "api": "API level 4" }]}
and my json respone is:
[{"post_id":"3","user_id":"1","post_inhalt":"lolli","likes":"1"},{"post_id":"4","user_id":"1","post_inhalt":"lala","likes":"2"}]
ther is my problem, i want one object with an array;
my php code looks like this.
<?php
$con=mysqli_connect("localhost","root","","my_db");
//echo "Welcome, I am connecting Android to PHP, MySQL";
if (mysqli_connect_errno($con))
{
//echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$user_id = "1";
//Für die Überprüfung
$result = mysqli_query($con, "SELECT * FROM post where user_id='$user_id'");
$response = array();
// fetch data in array format
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
//$response["code"] = 1;
// Fetch data of Fname Column and store in array of row_array
/*
$row_array["post"]['post_id'] = $row['post_id'];
$row_array["post"]['user_id'] = $row['user_id'];
$row_array["post"]['post_inhalt'] = $row['post_inhalt'];
$row_array["post"]['likes'] = $row['likes'];
*/
$row_array['post_id'] = $row['post_id'];
$row_array['user_id'] = $row['user_id'];
$row_array['post_inhalt'] = $row['post_inhalt'];
$row_array['likes'] = $row['likes'];
//push the values in the array
array_push($response,$row_array);
}
print json_encode($response);
mysqli_close($con);
?>
i want to put this in my android list view, but everytime i run my app , the error :
'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
because of that i think the data cant be found from my android. i am not the best in android, so maybe some one can help me.
here is my update of my php code:
//while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
//$response["code"] = 1;
// Fetch data of Fname Column and store in array of row_array
/*
$row_array["post"]['post_id'] = $row['post_id'];
$row_array["post"]['user_id'] = $row['user_id'];
$row_array["post"]['post_inhalt'] = $row['post_inhalt'];
$row_array["post"]['likes'] = $row['likes'];
*/
//$row_array = array();
$row_array['post_id'] = $row['post_id'];
$row_array['user_id'] = $row['user_id'];
$row_array['post_inhalt'] = $row['post_inhalt'];
$row_array['likes'] = $row['likes'];
//Funktioniert auch, gib aber nur ein array zurück
//$response[] = $row;
$response["post"] = array();
//push the values in the array
array_push($response["post"],$row_array);
}
print json_encode($response);
Add the row array to your resporse like this:
$respone["android"][$i] = $row_array;
ofcouse $i is the place in the array
Something like this:
$response["android"] = array();
$i = 0;
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$row_array['post_id'] = $row['post_id'];
$row_array['user_id'] = $row['user_id'];
$row_array['post_inhalt'] = $row['post_inhalt'];
$row_array['likes'] = $row['likes'];
$response["android"][$i] = $row_array;
}

Retrieve separate elements from a mySQL array field and iterate to create map

Because I'm using a map interface in Limesurvey, my mySQL database populates a "text" field in my table 'geo' like this:
27.059125784374068;-102.65625;CITY;STATE;COUNTRY;
The code I use in the presentation map looks for specific lat/lon information to iterate through the placemarks:
$encodedString = "";
$x = 0;
$result = mysql_query("SELECT * FROM `geo`");
while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
if ( $x == 0 )
{
$separator = "";
}
else
{
$separator = "****";
}
$encodedString = $encodedString.$separator.
"<p class='content'>
<br><b>Lon:</b> ".$row[0].
"<br><b>Lat:</b> ".$row[1].
"<br><b>SiteName: </b>".$row[2].
"<br><b>Country: </b>".$row[4].
"<br><b>PI: </b>".$row[5].
"</p>&&&".$row[1]."&&&".$row[2];
$x = $x + 1;
}
Am I making my life harder by trying to extract the lat/lon values from geoBlob? Is there a way to use the text field as it is?
I'm extracting the lon value like this:
$result = mysql_query("SELECT geoBlob FROM `geo`");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$arr = array();
foreach ($row as $k=>$v)
{
$breakEmUp = explode(";", $v);
$lon = $breakEmUp[0];
$arr[] = $lon;
}
$lonArray = join (", " , $arr);
But I don't know how to put the pieces together.
Getting way over my head here. Uncle! Any help appreciated.
Better you put each your text into differrent field, so make it easier than you must use string separator.

how to encode multiple rows from mysql into json using php

I am trying to encode all the rows of data i get from the DB into JSON and then process it at the client side but i can't seem to get it to work..My code is below
function getTopic($conn){
$response = array("error" => 0);
$qry = "SELECT original_title, content, time FROM topic WHERE vis = 1";
$result = $conn->prepare($qry);
$result->execute();
if($result->rowCount() > 0){
$output = $result->fetchall();
$response['text'] = $output['original_title'];
$response['test'] = $output['content'];
return json_encode($response);
//return $output;
}
Then i try to print the var_dump($response) but i get null values.. Although if i var_dump($output) i get all the rows in an array..accessing the array is the problem here now..i think
NB: i am using PDO
The problem is the $output is an array that you need to go through. Like:
function getTopic($conn){
$response = array("error" => 0);
$qry = "SELECT original_title, content, time FROM topic WHERE vis = 1";
$result = $conn->prepare($qry);
$result->execute();
if($result->rowCount() > 0){
$output = $result->fetchall();
foreach ($output as $o){
$response['text'] = $o['original_title'];
$response['test'] = $o['content'];
}
return json_encode($response);
}
}
This is for the last response, but if you want all, do:
function getTopic($conn){
$response = array('error'=>0);
$qry = "SELECT original_title, content, time FROM topic WHERE vis = 1";
$result = $conn->prepare($qry);
$result->execute();
if($result->rowCount() > 0){
$output = $result->fetchall();
foreach ($output as $o){
$response[] = array('text'=>$o['original_title'],'test'=>$o['content']);
}
return json_encode($response);
}
}
If you are only want one row add a limit to your MySQL statement.
$output is array of results. use a loop or if only one row u need do this:
function getTopic($conn){
$response = array("error" => 0);
$qry = "SELECT original_title, content, time FROM topic WHERE vis = 1";
$result = $conn->prepare($qry);
$result->execute();
if($result->rowCount() > 0){
$output = $result->fetchall();
$response['text'] = $output[0]['original_title'];
$response['test'] = $output[0]['content'];
return json_encode($response);
//return $output;
}

Categories

Resources