views:

208

answers:

4
+1  Q: 

iOS with JSON, PHP

I'm rather new to ios and json.

I've managed to create a db in mysql and used php to create a basic read and write php pages.

I'm using the TwitterHelper class from cs193p class for the presence assignment from Stanford to acces the php interface online and tie it to my ios code. I am getting an error which I can't solve.

Update:

Ok, here is my code:

<?php

include_once("JSON.php");
$json = new Services_JSON();

$link = mysql_pconnect("localhost", "user", "pass") or die("Could not connect");
mysql_select_db("mydb") or die("Could not select database");

$query = "SELECT * FROM tags";
$result = mysql_query($query);

$arr = array();
$rs = mysql_query("SELECT * FROM tags");

while($obj = mysql_fetch_object($rs)) {
    $arr[] = $obj;
}

Echo $json->encode($arr);
//Echo '{:'.$json->encode($arr).'}';

?>

The problem is that unless i remove the [] from $arr[], i get the answer to the php page enclosed in [] which the json fetch doesnt like and therefore throws and exception error and crashes my app.

If i remove it, the php page only returns 1 result...

A: 

the while loop is an iterator. if you want to fetch all the value from the database then the echo statement should be specified within the while loop.

Ibrahim Azhar Armar
A: 

What does Services_JSON do? In particular Service_JSON->encode(). And would a simple json_encode do the job? (since you do nothing else with the Service_JSON Object anyway)

Edit

$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
header('Content-type: application/json');
echo json_ecode($arr);

output: {"a":1,"b":2,"c":3,"d":4,"e":5}

Accordig to the PEAR::Services_JSON::docs

$json = new Service_JSON;
echo $json->encode($arr);

output: ["a":1,"b":2,"c":3,"d":4,"e":5]

maggie
A: 

Well, i read this array as an object from my iphone app for further processing...

mars
A: 

if i use:

echo json_ecode($arr);

it doesnt work, the page just comes up blank. Maybe it has something to do with my php service but it wont work, that i know for sure.

if i put the echo json inside the while loop, itll encode like this: {key:value, key:value}{key:value, key:value}{key:value, key:value}

whereas i need it like this:

{key:value, key:value},{key:value, key:value},{key:value, key:value}

mars
if you use json_encode you have to set the header to application/json by yourself (and take a look in your error logs)
maggie