Hello I am trying to use php to access my data base from a Swift app I am coding. So far reading the tables has been going great, except now I am trying to read a table that has multiple rows containing json. This has been throwing errors and I can not seem to get the final output to equal what I want, or anything that works with the swift code for that matter. The json originally just outputted as null. Upon researching how to fix that I tried utf8_encode() but that gave too many extra characters and the Swift code in the app couldn't make sense of it. When outputting just one of the rows it comes out fine, Its when I try putting them in one associative array to out put as json is when they come up as null.
PHP Code:
$sql = "Select * FROM User WHERE Id = '".$UserId."' LIMIT 1";
mysql_select_db($database, $User);
$result = mysql_query($sql , $User) or die(mysql_error());
$FleetRaw = mysql_fetch_assoc($result);
$Fleet1 = $FleetRaw['Fleet1'];
$Fleet2 = $FleetRaw['Fleet2'];
$Fleet3 = $FleetRaw['Fleet3'];
$Fleet4 = $FleetRaw['Fleet4'];
$Fleet5 = $FleetRaw['Fleet5'];
$Fleet6 = $FleetRaw['Fleet6'];
$Fleets = array("1"=>$Fleet1,"2"=>$Fleet2,"3"=>$Fleet3,"4"=>$Fleet4,"5"=>$Fleet5,"6"=>$Fleet6);
//Output 1
echo $Fleets["1"]."<br><br><br>";
//Output 2
echo json_encode(utf8_encode($Fleets["1"]))."<br><br><br>";
//Output 3
echo json_encode($Fleets);
?>
Outputs:
Output 1:
{ “status” : 3, “game” : 0, “ships” : { "1" : { "level" : 0, "className" : "LighteningShip", "posX" : 100, "health" : 50, "posY" : 100 }, "3" : { "level" : 0, "className" : "LighteningShip", "posX" : 100, "health" : 50, "posY" : -100 }, "2" : { "level" : 0, "className" : "LighteningShip", "posX" : 100, "health" : 50, "posY" : 0 }, "0" : { "level" : 0, "className" : "MotherShip", "posX" : 0, "health" : 100, "posY" : 0 } } }
Output 2:
"{\n\u0093status\u0094 : 3,\n\u0093game\u0094 : 0,\n\u0093ships\u0094 : {\n \"1\" : {\n \"level\" : 0,\n \"className\" : \"LighteningShip\",\n \"posX\" : 100,\n \"health\" : 50,\n \"posY\" : 100\n },\n \"3\" : {\n \"level\" : 0,\n \"className\" : \"LighteningShip\",\n \"posX\" : 100,\n \"health\" : 50,\n \"posY\" : -100\n },\n \"2\" : {\n \"level\" : 0,\n \"className\" : \"LighteningShip\",\n \"posX\" : 100,\n \"health\" : 50,\n \"posY\" : 0\n },\n \"0\" : {\n \"level\" : 0,\n \"className\" : \"MotherShip\",\n \"posX\" : 0,\n \"health\" : 100,\n \"posY\" : 0\n }\n}\n}"
Output 3:
{"1":null,"2":null,"3":null,"4":null,"5":null,"6":null}
Output 1 is exactly the format I want (the one Swift understands), except it is only one of the six rows (Also app rejects this form because it is not json_encode before echoing). Output 2 is an example of one of the six rows that when used utf8_encode() before saved to the array gives to many extra characters, however it does output as not null when put into an array of the six. Output 3 is what I want to eventually output, just without the null.
The ideal situation would be to combine outputs 1 and 3 so that I can output an array of six with them looking like Output 1. Also the app has only worked when I json_encode what I echo. If there is anyone possible to accomplish this please let me know!!
Thanks!!
closest attempt, working but double the data?
$Fleet1 = $FleetRaw['Fleet1'];
$Fleet2 = $FleetRaw['Fleet2'];
$Fleet3 = $FleetRaw['Fleet3'];
$Fleet4 = $FleetRaw['Fleet4'];
$Fleet5 = $FleetRaw['Fleet5'];
$Fleet6 = $FleetRaw['Fleet6'];
$Fleets = array("1"=>$Fleet1,"2"=>$Fleet2,"3"=>$Fleet3,"4"=>$Fleet4,"5"=>$Fleet5,"6"=>$Fleet6);
// Convert an array of JSON-Strings to unified array of structured data..
foreach ( $Fleets as $key => $sJSONString ){
$FleetRaw[$key] = json_decode($sJSONString);
}
// Now return the whole lot as a json-string to the client
header("Content-type: application/json"); // My assumption of your model..
print json_encode($Fleets);
There are two problems, as far as I can see:
Issue A: Broken JSON in database
Output 1:
{ “status” : 3, “game” : 0, “ships” : { "1" : { ... etc
Those characters “” are not legal in JSON... so you won't be able to parse the data you have within your database as JSON. You will have to replace them with legitimate " characters. Where did the JSON come from?
Issue B: Mixed string & structure
You're mixing JSON-as-a-string (coming from the database) and an array data-structure in PHP (the array of rows from the database) that you wish to represent as JSON.
So to fix that should be doing something like:
<?php
// Convert an array of JSON-Strings to unified array of structured data..
foreach ( $FleetRaw as $key => $sJSONString ){
$FleetRaw[$key] = json_decode($sJSONString);
}
// Now return the whole lot as a json-string to the client
header("Content-type: application/json"); // My assumption of your model..
print json_encode($FleetRaw);
?>
What this should output is an array of objects:
[{ "status" : 3, "game" : 0, "etc" : "..." },{ "status" : 99, "game" : 123, "etc" : "..." },{ "status" : 345, "game" : 456, "etc" : "..." },{ .. }]
Note on your 'nulls' & UTF8 (Output 3)
I would imagine your nulls are caused by PHP failing to even encode the JSON-strings as strings because they contain UTF8 characters -- which is why the Output 3 shows nulls. But those encoding issues may just be those dodgy “” you have in your database.
If you fix issue A you may find you fix Output 3 too. Though this doesn't preclude you from having to address issue B. Output 3 would become an array of your JSON-strings (represented as strings that just happen to look like JSON). Issue B will then sort you out.
Incidentally: http://php.net/manual/en/function.json-last-error.php should help you narrow down any remaining issues with your source JSON if the above doesn't.
Hope this helps! J.
I'm not sure but I think the problem is that your fleet data is already in json format. That is way the first output echoes what you want. In the second output you just encode json data from Fleets["1"] into utf8 and then encode it into json again). The third output with the same problem but this time you just trying to reencode your json data into json again.
Try this one:
$Fleet1 = json_decode($FleetRaw['Fleet1']);
$Fleet2 = json_decode($FleetRaw['Fleet2']);
$Fleet3 = json_decode($FleetRaw['Fleet3']);
$Fleet4 = json_decode($FleetRaw['Fleet4']);
$Fleet5 = json_decode($FleetRaw['Fleet5']);
$Fleet6 = json_decode($FleetRaw['Fleet6']);
You get objects.
$Fleets = array("1"=>$Fleet1,"2"=>$Fleet2,"3"=>$Fleet3,"4"=>$Fleet4,"5"=>$Fleet5,"6"=>$Fleet6);
You get array of objects
echo json_encode($Fleets);
You should get a vaild json data.
Try to json_decode() in last line as follows:
$Fleets["1"] = '{ "status" : 3, "game" : 0, "ships" : { "1" : { "level" : 0, "className" : "LighteningShip", "posX" : 100, "health" : 50, "posY" : 100 }, "3" : { "level" : 0, "className" : "LighteningShip", "posX" : 100, "health" : 50, "posY" : -100 }, "2" : { "level" : 0, "className" : "LighteningShip", "posX" : 100, "health" : 50, "posY" : 0 }, "0" : { "level" : 0, "className" : "MotherShip", "posX" : 0, "health" : 100, "posY" : 0 } } }';
//Output 1
echo $Fleets["1"]."<br><br><br>";
//Output 2
echo json_encode(utf8_encode($Fleets["1"]))."<br><br><br>";
//Output 3
echo '<pre>';
print_r(json_decode($Fleets["1"]), true);
echo json_decode($Fleets["1"]);
Your output 1 should be :-
{ "status" : 3, "game" : 0, "ships" : { "1" : { "level" : 0, "className" : "LighteningShip", "posX" : 100, "health" : 50, "posY" : 100 }, "3" : { "level" : 0, "className" : "LighteningShip", "posX" : 100, "health" : 50, "posY" : -100 }, "2" : { "level" : 0, "className" : "LighteningShip", "posX" : 100, "health" : 50, "posY" : 0 }, "0" : { "level" : 0, "className" : "MotherShip", "posX" : 0, "health" : 100, "posY" : 0 } } }
It may help you.
Related
{
"_id" : ObjectId("5844dd1d3627570f004612a5"),
"updatedBy" : ObjectId("57c4799d23be243006e188f8"),
"updatedAt" : ISODate("2016-12-21T10:08:10.211Z"),
"createdBy" : ObjectId("5801b7195248ef0e00948934"),
"createdAt" : ISODate("2016-12-05T03:21:01.660Z"),
"stock" : 50,
"price" : 15000,
"owner" : ObjectId("5801b7195248ef0e00948934"),
"type" : ObjectId("57dce9ad07f96c701c0b24a8"),
"isValid" : true,
"grade" : "Grade A",
"__v" : 0
}
i want to ask how to insert owner data and also type data as ObjectID to mongoDB with php
when i just insert data, it wont changes to object id
anyone?
i got the answer.
just use like this :
$id_param = 1270982704y1024kjh12kj4h; new MongoId($id_param)
thanks a lot your for help
May be this is a silly question, but anyway I have the doubt.
Please take a look at this query:
db.posts.find({ "blog": "myblog",
"post_author_id": 649,
"shares.total": { "$gt": 0 } })
.limit(10)
.skip(1750)
.sort({ "shares.total": -1, "tstamp_published": -1 });
actually I see into the mongodb profiler this report:
mongos> db.system.profile.find({ nreturned : { $gt : 1000 } }).limit(10).sort( { millis : 1 } ).pretty();
{
"ts" : ISODate("2013-04-04T13:28:08.906Z"),
"op" : "query",
"ns" : "mydb.posts",
"query" : {
"$query" : {
"blog" : "myblog",
"post_author_id" : 649,
"shares.total" : {
"$gt" : 0
}
},
"$orderby" : {
"shares.total" : -1,
"tstamp_published" : -1
}
},
"ntoreturn" : 1760,
"nscanned" : 12242,
"scanAndOrder" : true,
"nreturned" : 1760,
"responseLength" : 7030522,
"millis" : 126,
"client" : "10.0.232.69",
"user" : ""
}
Now the question is: why mongodb is returning 1760 documents when I have explicitly asked to skip 1750?
This is my current Mongodb version, in cluster/sharding.
mongos> db.runCommand("buildInfo")
{
"version" : "2.0.2",
"gitVersion" : "514b122d308928517f5841888ceaa4246a7f18e3",
"sysInfo" : "Linux bs-linux64.10gen.cc 2.6.21.7-2.ec2.v1.2.fc8xen #1 SMP Fri Nov 20 17:48:28 EST 2009 x86_64 BOOST_LIB_VERSION=1_41",
"versionArray" : [
2,
0,
2,
0
],
"bits" : 64,
"debug" : false,
"maxBsonObjectSize" : 16777216,
"ok" : 1
}
Now the question is: why mongodb is returning 1760 documents when I have explicitly asked to skip 1750?
Because the server side skip() does exactly that: it iterates over the first 1750 results and then gets 10 more (according to the limit).
As #devesh says, this is why very large pagination should be avoided since MongoDB does not make effective use of an index for skip() or limit().
I think you have hit a bulls eye , I think it is reason why mongoDB document asks us to avoid the large skips http://docs.mongodb.org/manual/reference/method/cursor.skip/ . Please have a look here It will answer your outcome . Use some other key which will be used with $gt operator will be much faster. Like Datetime stamp of last key in the page 1 then use the $get on the datetime.
The cursor.skip() method is often expensive because it requires the server to walk from the beginning of the collection or index to get the offset or skip position before beginning to return result
Is there a way to perform REST actions in the middle of executing an action? For example, if I perform GET /index.php/book/1 I might receive the following:
[{
"id" : 1,
"title" : "This is a book.",
"owner_id" : 4
}]
But what I'd like to do is before returning the above object, perform a GET /index.php/user/4 so the end result is:
[{
"id" : 1,
"title" : "This is a book.",
"owner" : {
"id" : 4,
"name" : "John Smith",
"age" : 40
}
}]
There is even simple way of doing this with Restler by internally calling another api method directly instead of wasting one call to the server
class User{
public function get($id, $includeOwner = true){
$result = getUserFromDB($id)
if($includeOwner){
$result['owner'] = $this->get(getOwnerIdFromDB($id),false);
}
}
return $result;
}
HTH
I am saving "Article" in MongoDB as bellow with _id of integers.
When I want to delete the article with the _id in php, nothing happens.
The code I use is:
$result = $db->arcitle->remove(
array("_id" =>intVal(41)),
array('safe' => true)
);
I have tried both with and without using "safe" option, neither works. When I echo $result, it is bool(true).
Any suggestion is much appreciated!
{ "_id" : 41,
"when" : Date( 1333318420855 ),
"publisher" : "5",
"title" : "10 Steps To The Perfect Portfolio Website",
"raw" : "",
"preview" : "",
"thumbnail" : "",
"content" : [
"{}" ],
"tags" : null,
"votes" : 0,
"voters" : [],
"comments" : [] }
you've got a spelling mistake in the collection name.
$result = $db->arcitle->remove(
Should probably be:
$result = $db->article->remove(array("_id" => 41));
The safe option will not confirm something was deleted, only that there was no error. Remove will not trigger an error deleting something that doesn't exist.
> db.foo.remove({_id: "I don't exist"})
> db.getLastError()
null
Note that you don't need to recast an integer as an integer - and if you do need to cast input as an integer - use a cast statement:
$string = "42";
$int = (int) $string; // $int === 42
I am creating an application that has several servers running at the same time and several process on each server all of those are processing data making query/updates and inserts. So a total of 35+ concurrent connections are being made at all times. These servers are all processing data that is being sent to a single mongodb server (mongod). I am not sharding my database at the moment. The problem is that I am being limited by my mongodb server. Whenever I add more servers the queries/updates/inserts are running slower (they take more time). I was running this mongohq.com, then I just recently created my own amazon server for mongod but I am still getting nearly the same result. List below is my db.serverStatus({}). I am somewhat new to mongodb but basically I need to know how to speed up the process for the amount of concurrent operations going on with my mongo server. I need it to be able to handle a lot of requests. I know sharding is a possible way around this but if it is at all possible can you list some other solutions available. Thanks.
> db.serverStatus({})
{
"host" : "ip-10-108-245-21:28282",
"version" : "2.0.1",
"process" : "mongod",
"uptime" : 11380,
"uptimeEstimate" : 11403,
"localTime" : ISODate("2011-12-13T22:27:56.865Z"),
"globalLock" : {
"totalTime" : 11380429167,
"lockTime" : 86138670,
"ratio" : 0.007569017717695356,
"currentQueue" : {
"total" : 0,
"readers" : 0,
"writers" : 0
},
"activeClients" : {
"total" : 35,
"readers" : 35,
"writers" : 0
}
},
"mem" : {
"bits" : 64,
"resident" : 731,
"virtual" : 6326,
"supported" : true,
"mapped" : 976,
"mappedWithJournal" : 1952
},
"connections" : {
"current" : 105,
"available" : 714
},
"extra_info" : {
"note" : "fields vary by platform",
"heap_usage_bytes" : 398656,
"page_faults" : 1
},
"indexCounters" : {
"btree" : {
"accesses" : 798,
"hits" : 798,
"misses" : 0,
"resets" : 0,
"missRatio" : 0
}
},
"backgroundFlushing" : {
"flushes" : 189,
"total_ms" : 29775,
"average_ms" : 157.53968253968253,
"last_ms" : 185,
"last_finished" : ISODate("2011-12-13T22:27:16.651Z")
},
"cursors" : {
"totalOpen" : 34,
"clientCursors_size" : 34,
"timedOut" : 0,
"totalNoTimeout" : 34
},
"network" : {
"bytesIn" : 89743967,
"bytesOut" : 59379407,
"numRequests" : 840133
},
"opcounters" : {
"insert" : 5437,
"query" : 8957,
"update" : 4312,
"delete" : 0,
"getmore" : 76,
"command" : 821388
},
"asserts" : {
"regular" : 0,
"warning" : 0,
"msg" : 0,
"user" : 0,
"rollovers" : 0
},
"writeBacksQueued" : false,
"dur" : {
"commits" : 29,
"journaledMB" : 0.147456,
"writeToDataFilesMB" : 0.230233,
"compression" : 0.9999932183619632,
"commitsInWriteLock" : 0,
"earlyCommits" : 0,
"timeMs" : {
"dt" : 3031,
"prepLogBuffer" : 0,
"writeToJournal" : 29,
"writeToDataFiles" : 2,
"remapPrivateView" : 0
}
},
"ok" : 1
}
What is surprising about more load generating higher response times from mongod? There are a few possible reasons for degradation of performance.
For example, every write to mongod uses a process wide write lock. So the more servers you add the more updates will be attempted (assuming update load is about stable per server) and thus the longer the process will spend in write lock. You can keep an eye on this through mongostat's "locked %" field.
Additionally if you use JS powered functionality (m/r, db.eval(), etc.) these operations cannot be executed concurrently by mongod due to the fact that each mongod has a single JavaScript context (which is single threaded).
If you want a more specific analysis then you might want to consider posting exact numbers. How many reads and writes per second, what are the query plans for the queries you execute, what effect does adding an additional app server have on your overall database performance, etc.