Array always starts at one, empty zero - java

I'm trying to read my MySQL data and put it as JSON. But I just want a single JSON Object, it tries giving me a JSONArray, but that array is empty.
This is what it gives me, top is JSON, bottom is simple array.
[
[],
{
"id": "1",
"description": null,
"copyright": "© Ian Ransley, flickr.com\/CC BY 2.0"
}
]
Array
(
[0] => Array
(
)
[1] => Array
(
[id] => 1
[description] =>
[copyright] => © Ian Ransley, flickr.com/CC BY 2.0
)
)
As you can see, the zero index is empty for some reason, and right before my object starts there is an opening and closing bracket ([]), which makes my android app recognize that as an array instead of object.
here's my php code:
<?php
header('Content-type: text/plain');
$connection = mysqli_connect("localhost", "bananatime", "Yoyobanana", "bananatime")
or die("Error " . mysqli_error($connection));
if(isset($_GET['id'])){
$sql = "SELECT * FROM bananas WHERE id = '".$_GET['id']."' ORDER BY id";
}else{
$sql = "SELECT * FROM bananas ORDER BY id";
}
$result = mysqli_query($connection, $sql) or die("Error in Selecting " .mysqli_error($connection));
$array[] = array();
while($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
array_push($array, $row);
}
array_values($array);
echo json_encode($array, JSON_PRETTY_PRINT);
echo "\n\n";
print_r($array);
mysqli_close($connection);
?>

change $array[] = array(); to $array = array();

array_push() was the problem. I had to use $array = $row;

Related

Who use NgFor in my case?

i have a list of horse race result in my database.
In my database, i have 3 table :
horse (cheval in french) with : id, name ...
race (course in french) with : id, name ...
and resultrace (resultatcourse in french) the id of the horse (cheval) and the id of the race (course) and position in the race(first, second ...)
When i want to use it in a NgFor to do a list of all my race, who can i can use only the race's name, the horse's name and his position ?
My JSON:
[
{id: 1, nom: "Valdack", place: 2, course: 1},
{id: 5, nom: "Flying fox", place: 1, course: 1},
{id: 17, nom: "Dane Dream", place: 4, course: 1}
]
My html code :
<ion-item *ngFor="let item of items; ">
<h2>{{ item.nom (name of the race) }} | {{ item.nom (name of the horse) }} | N°{{ item.place }} </h2>
</ion-item>
My php :
try {
$stmt = $pdo->query('SELECT course.id, course.nom , cheval.id, cheval.nom , resultatcourse.place, resultatcourse.course, resultatcourse.place FROM course, cheval, resultatcourse WHERE resultatcourse.course = course.id AND resultatcourse.cheval = cheval.id');
while($row = $stmt->fetch(PDO::FETCH_OBJ))
{
// Assign each row of data to associative array
$data[] = $row;
}
// Return data as JSON
echo json_encode($data);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
And my java :
load() : void
{
this.http.get('http://localhost/wequida/retrieve-resultatcourse.php').subscribe((data : any) =>
{
console.dir(data);
this.items = data;
},
(error : any) =>
{
console.dir(error);
});
}
My table horse and my table race have 2 same columns : id and name, maybe it's the problem ?
I find the solution ! (Thk user184994 !)
In my php :
try {
$stmt = $pdo->query('SELECT course.id, course.nom as coursenom, cheval.id, cheval.nom as chevalnom, resultatcourse.place, resultatcourse.course, resultatcourse.place FROM course, cheval, resultatcourse WHERE resultatcourse.course = course.id AND resultatcourse.cheval = cheval.id');
while($row = $stmt->fetch(PDO::FETCH_OBJ))
{
// Assign each row of data to associative array
$data[] = $row;
}
// Return data as JSON
echo json_encode($data);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
I had an as to differentiate horse's name and race's name
In my html :
<ion-item *ngFor="let item of items; ">
<h2>{{ item.coursenom }} | {{ item.chevalnom }} | N°{{ item.place }} </h2>
</ion-icon></button>
</ion-item>
I use the as name

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

passing special characters from mysqli database to android app using php

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']);
...

how to read this json array in java

i have a json array generated by this php:
$filtros=mysql_query("SELECT id_transporte FROM user_trans WHERE id_usuario = '".$id_usuario ."'");
for($i=0; $i<=mysql_num_rows($filtros); $i++){
$rs[]= mysql_fetch_array($filtros,MYSQL_ASSOC);
}
foreach($rs as $valor){
if (is_array($valor)) {
foreach($valor as $valor1){
$reportes[]= mysql_query("
SELECT * FROM transportes
WHERE id_transporte='".$valor1."'
ORDER BY fecha_reporte DESC ");
}
}
}
foreach($reportes as $valor){
if($valor != false){
for($i=0; $i<=mysql_num_rows($valor); $i++){
$row[]= mysql_fetch_array($valor,MYSQL_ASSOC);
}
}
}
print_r (json_encode($row));
which returns:
[{"id_report":"73","id_transport":"624","txt_report":"Report0"},
{"id_report":"46","id_transport":"624","txt_report":"Report1"},false,
{"id_report":"74","id_transport":"9999","txt_report":"Report2"},
{"id_report":"52","id_transport":"9999","txt_report":"Report3"},false]
well, i try to read that, but java only read until "false"...
that array are 2 arrays which joined and printed, so i try this:
$row1=str_replace ( "false" , '{"salto":1}' , $row );
$row1[]=false;
print_r (json_encode($row1));
that returns the sames but "" instead "false" and a "false" in the end
but java continues reading until now the ""
i use that for read json
if (jdata!=null && jdata.length() > 0){
JSONObject json_data = null;
try{
System.out.println( jdata.length() );//java there print all the array length ignoring the "false" o ""
for (int i=0; i < jdata.length(); i++){
reportsId[i]=jdata.getJSONObject(i).getString("id_report");
transportId[i]=jdata.getJSONObject(i).getString("id_transport");
txt_report[i]=jdata.getJSONObject(i).getString("txt_report");
System.out.println( " i= "+ i);
}
}
}catch(Exception e3){}
so my question is how read this, or change some lines on php
First of all in your PHP you shouldn't use mysql_* functions as they are deprecated and dangerous. Your code could be vulnerable to SQL Injection. Consider using PDO
You could probably make this much faster by running a single query that would also get rid of the false values. You certainly don't need to stuff everything into an array and then loop over it.
Here's my take:
$resp = mysql_query("SELECT t.* FROM transportes t
JOIN user_trans ut ON t.id_transporte=ut.id_transporte
WHERE ut.id_usuario='$id_usuario'
ORDER BY fecha_reporte DESC");
if(!$resp) {
// handle the error!
die(mysql_error())
}
$output = [];
while( $row = mysql_fetch_assoc($resp) ) {
$output[] = $row;
}
print_r(json_encode($output));
This should solve your problem with false values because they are likely due to the second query not being checked for errors.
The JSON in not well formed.
There's a comma missing after "id_report":"46"

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