how to encode multiple rows from mysql into json using php - java

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

Related

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

Array always starts at one, empty zero

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;

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.

Is there a way to save session keys into mysql 5.5?

A company that I'm working now is going to use DB sessions to organize their servers. I have no choice to refuse it :(
The sample php code they were gonna use was
sessioninit.php
<?
/* ------------------------------------------------------------------------
* Create a new database in MySQL called "sessions" like so:
*
* CREATE TABLE ucnovel_session (
* sesskey char(32) not null,
* expiry int(11) unsigned not null,
* value text not null,
* PRIMARY KEY (sesskey)
* );
*/
$SESS_DBH = "";
$SESS_LIFE = get_cfg_var("session.gc_maxlifetime");
function sess_open($save_path, $session_name)
{
global $SESS_DBH;
$sv = "192.168.0.3";
$SESS_DBH = mysql_pconnect($sv, "ucnovel", "비번") or die("Can't connect to SQL Server");
mysql_select_db("hotdog", $SESS_DBH) or die("Can't connect to SQL Server");
return true;
}
function sess_close()
{
return true;
}
function sess_read($key)
{
global $SESS_DBH, $SESS_LIFE;
//echo $key;
$qry = "SELECT value FROM ucnovel_session WHERE sesskey = '$key' AND expiry > " . time();
$qid = mysql_query($qry, $SESS_DBH);
if (list($value) = mysql_fetch_row($qid)) {
return $value;
}
return false;
}
function sess_write($key, $val)
{
global $SESS_DBH, $SESS_LIFE;
$expiry = time() + $SESS_LIFE;
$value = addslashes($val);
$qry = "SELECT COUNT(*) FROM ucnovel_session WHERE sesskey='$key'";
$qid = mysql_fetch_array(mysql_query($qry, $SESS_DBH));
if($qid[0]>0) {
$qry = "UPDATE ucnovel_session SET expiry = $expiry, value = '$value' WHERE sesskey = '$key'"; // AND expiry > " . time();
$qid = mysql_query($qry, $SESS_DBH);
} else {
$qry = "INSERT INTO ucnovel_session SET expiry = $expiry, value = '$value', sesskey = '$key'";
$qid = mysql_query($qry, $SESS_DBH);
}
return $qid;
}
function sess_destroy($key)
{
global $SESS_DBH;
$qry = "DELETE FROM ucnovel_session WHERE sesskey = '$key'";
$qid = mysql_query($qry, $SESS_DBH);
return $qid;
}
function sess_gc($maxlifetime)
{
global $SESS_DBH;
$qry = "DELETE FROM ucnovel_session WHERE expiry < " . time();
$qid = mysql_query($qry, $SESS_DBH);
return mysql_affected_rows($SESS_DBH);
}
session_set_save_handler("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");
session_set_cookie_params(0, "/", "ucnovel.com", false, false);
session_start();
?>
sessiontest.php
<?
include "sessioninit.php";
$old = $_COOKIE[test_sess2];
$new = rand()%10000;
$_COOKIE[test_sess2] = $new;
setcookie("test_sess2", $new);
echo "OLD ".$old."<br>"."NEW ".$new;
$old = $_SESSION[test_sess];
$new = rand()%10000;
$_SESSION[test_sess] = $new;
$_SESSION[test_ip] = $REMOTE_ADDR;
echo "<br><br>OLD ".$old."<br>"."NEW ".$new;
?>
I understand that they override the session handler and customized it. But I can't find any references on how to do it in Java.
Some people says that overriding HttpSession is a way. But I still can't understand how to do this. Also, I don't know if DTOs will save in the DB :S
I'm using Spring 3.1 right now, and the server is MySQL 5.5
Is there any samples that I can understand how to do it? or maybe a plugin that helps it?

Categories

Resources