How to use mongodb _id to find record - php

I am doing project with mongodb and php. so I am trying to find record using it _id. here I post json value like this way
{"_id": {"$id": "513ea9d4a00b2ade09000001"}}
then I get this value and decode it and use to find like this way
$obj = json_decode( $json, true);
$result = $collection->find($obj);
but above code give error because in the json their is a key like $id. so how I solve above problem please help me.

Please follow this example:
// This is only a string, this is NOT a MongoId
$mongoid = '4cb4ab6d7addf98506010000';
// You will not find anything by searching by string alone
$nothing = $collection->find(array('_id' => $mongoid));
echo $nothing->count(); // This should echo 0
// THIS is how you find something by MongoId
$realmongoid = new MongoId($mongoid);
// Pass the actual instance of the MongoId object to the query
$something = $collection->find(array('_id' => $realmongoid));
echo $something->count(); // This should echo 1
You could find more info here.

From a JSON string it is slightly different to all the examples shown currently.
Since you now have an object of an assoc array which looks like:
array(
'_id' => array(
'$id' => "513ea9d4a00b2ade09000001"
)
)
You must extract that $id property and cast it to a MongoId like so:
$db->collection->find(new MongoId($obj['$id']));
That will find your record.

To find document using '_id' you have to typecast it to MongoId Object. This can be done by passing array('_id' => new MongoId($valOf_id) ) in the find query.
I did not write a verbose answer as I am sure this is enough for you to get the point right :-)

Related

At a loss with JSON, PHP, AS3: Cannot trace correct value

I have used JSON objects before and they work perfectly but the JSON objects that I made before have been from a result of fetched MySQL entries. Now, I am trying to make my own JSON object through an array in PHP and it shows correctly in the database but I cannot access any of the values like before.
$chatArray = array(
array(
'chatusername' => 'Troy',
'chatuserid' => '123',
'chatmessage' => 'Hello World'
),
array(
'chatusername' => 'Nick',
'chatuserid' => '124',
'chatmessage' => 'Testing'
));
$inputArray = json_encode($chatArray);
That is what I input into my database and like I said it works good. Then I call for it in a separate .php and get this
{"chat":"[{\"chatuserid\": \"123\", \"chatmessage\": \"Hello World\", \"chatusername\": \"Troy\"}, {\"chatuserid\": \"124\", \"chatmessage\": \"Testing\", \"chatusername\": \"Nick\"}]"}
It throws the "chat" out front which is the column name in my database which I am not sure why.
When I trace it I can only seem to trace it by
var messageArray:Object = JSON.parse(event.target.data);
trace(messageArray.chat);
Any time I try to reference say messageArray.chat.chatusername it returns an error.
I'm sorry I know it is probably a simple solution but I have been searching and working at it for a few hours now.
Any help is much appreciated! Thank you!
From the PHP code that generates your JSON output:
$stmt = $conn->prepare("SELECT chat FROM markerinfo WHERE markerid='$chatid'");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($result);
Keep in mind that the chat column in your database contains a JSON-string.
This code is not decoding the JSON-string in your database, so $result will be an array containing a JSON-string as well:
$result = [
'chat' => '[{"chatusername":"Troy","chatuserid":"123","chatmessage":"Hello World"},{"chatusername":"Nick","chatuserid":"124","chatmessage":"Testing"}]'
];
By passing that array through json_encode(), you're double-encoding your JSON-string.
For your purposes, you can probably get away with:
echo $result['chat'];
But, if you want the chat column name to be included in your output, you will have to decode the stored JSON first:
$result['chat'] = json_decode($result['chat']);
echo json_encode($result);
Probably this is related to the php side when it encodes your array, it will escape it with slashes, and this confuses the JSON parsing in your JS side. Try to add the JSON_UNESCAPED_SLASHES option to your json_encode function like this:
$inputArray = json_encode($chatArray, JSON_UNESCAPED_SLASHES);
Check the json_encode function documentation for more details:
http://php.net/manual/en/function.json-encode.php

how to decode the encoded array value

I want to decode the array value in web service.I need to decode 'CONTENT_VALUES' field which has name and value as its object and pass it in json.ID and USER_ID return correct value(separate field) but name and question returns null. I want to decode 'ques' => $datas->name, 'answer' => $datas->value.value of CONTENT_VALUES=[{"name":"radio","value":"","sur_id":"3","user_id":"admin#gmail.com","pagename":"question_response"},{"name":"true","value":""}]
$query1 = mysql_query("select * from `$prefix.response` where ID='$sur_id'");
while ($fetch = mysql_fetch_array($query1)) {
$content = $fetch['CONTENT_VALUES'];
$datas = json_decode($content);
$test[] = array('ID' => $fetch['ID'], 'USERID' => $fetch['USER_ID'], 'ques' => $datas->name, 'answer' => $datas->value);
}
Take a look at http://php.net/manual/en/function.json-decode.php.
This will describe how to convert a JSON string into a PHP object or array.
When you get stuck more with this you can fairly simple google "php decode json" and find plenty helpful resources.
Edit: Read the question too quick just before and understood it wrong, have you tried checking the return result of your $datas = json_decode($content) statement? Does CONTENT_VALUES actually contain JSON encoded data? Does the decoded object actually contain name and value?
May be you should set use mb_convert_encoding before decoding like this
$content = $fetch['CONTENT_VALUES'];
$content_value= mb_convert_encoding($content ,"UTF-8");
$datas = json_decode($content_value);

Referencing PHP arrays returned from MySQL for a JSON API

I have a result, $result, returned from an SQL query which contains the following data: [{"TOTAL":"12345"}]
I want to put that result into a JSON API with a route of, say, /api/total/ and have it return: {total:12345}. I'll be setting the first half of that manually, e.g. 'total' => whatever in the Slim framework.
$app->render(200, array(
'total' => $result["TOTAL"]
)
);
How do I reference 12345 from the returned array? Doing $result["TOTAL"] doesn't work.
The result looks like [{"TOTAL":"12345"}]?
So you have to json_decode it first.
$decodedResult = json_decode($result, true);
echo $decodedResult[0]['TOTAL'];
Use this code , you will get the value.
$result = '[{"TOTAL":"12345"}]';
$res = json_decode($result);
echo $res[0]->TOTAL;
Please try this
$res = json_decode($result);
even though there is only one object in the array, it is still an array so you need to reference the object's index.
$result[0]["TOTAL"]

What kind of php array is this and how do I edit it?

I am working with a project that is coded in php OOP. I have created a form that post back to itself and gets those values and puts them into a predefined array format. I say predefined because this is the way the previous coder has done it:
$plane->add(array('{"name":"Chris","age":"22"}','{"name":"Joyce","age":"45"}'));
So when I get my values from the $_POST array, I thought it would be simple, so I tried
$plane->add(array("{'name':$customerName,'age':$customerAge}"));
This is triggering an error though, it seems it's passing the actual name of the variable in as a string instead of it's value. So how do I pass those values in to that function. While we are on it, can someone explain what kind of array that is, I thought arrays were always $key=>value set, not $key:$value.
As other comments and answers have pointed out, the data is being serialized in a format known as JSON. I suggest reading up on json_encode() and json_decode()
To make your example work, you would have to do:
$data = array("name" => $customerName, "age" => $customerAge);
$plane->add(array(json_encode($data));
That looks like json:
http://sandbox.onlinephpfunctions.com/code/e1f358d408a53a8133d3d2e5876ef46876dff8c6
Code:
$array = json_decode('{"name":"Chris","age":"22"}');
print_r( $array );
And you can convert an array to json with:
$array = array("Customer" => "John");
$arrayJson = json_encode( $array);
So to put it in your context:
$array = array("Name"=>"Chris", "age" => 22);
$array2 = array("Name"=>"John", "age" => 26);
$plane->add(array( json_encode( $array),json_encode( $array2) );
It looks like it could be JSON, but might not be.
Be careful to quote everything like they have done, you didn't have any quotes around the name or age.
I've added the same sort of quotes, and used the backslashes so that PHP doesn't use them to end the string:
$plane->add(array("{\"name\":\"$customerName\",\"age\":\"$customerAge\"}"));
Be wary of user data, if $customerName and $customerAge come from POST data, you need to properly escape them using a well tested escaping function, not something you just hack together ;)
It looks like your array is an array of JSON encoded arrays. Try using:
$plane->add(array('{"name":"' . $nameVar . '","age":"' . $ageVar . '"}', ...));
If you use the following:
echo json_encode(array('name' => 'Me', 'age' => '75'), array('name' => 'You', 'age' => '30'));
You will get the following string:
[{"name":"Me","age":"75"},{"name":"You","age":"30"}]
I believe you are getting an error because what you are trying to pass to the function is not JSON while (It looks like ) the function expects an array json strings, Manually trying to write the string might not be a good idea as certain characters and type encode differently. Best to use json_encode to get you json string.
$plane->add(array(json_encode(array('name'=>$customerName,'age'=>$customerAge))));

Need PHP help assigning a piece of data from an Amazon S3 query to a variable

I'm using the AWS PHP SDK along with the code listed below to return a list of objects associated with a folder on my Amazon S3 service:
$s3 = new AmazonS3();
$response = $s3->list_objects($bucket, array(
'prefix' => 'myfolder/'
));
print_r($response->body);
I don't want to use "print_r" part.
The $response seems to be an array with a bunch of stuff in it:
Key, LastModified, ETag, Size, Owner
What would the PHP code look like that would loop through $response and assign one of the bits to a variable. For example, one piece of data in $response is "Key" that looks something like this:
[Key] => myfolder/myfile.pdf
what I need is:
myfolder/myfile.pdf
Please provide the code I would need to loop through the data within $response and assign each instance of "KEY" to a variable called: $haasfilepath.
Thanks!
It has been awhile since I've used php, but this should be work if I understand your problem.
If $response is an array with each element containing an associative array for the matching object.
$hassfilepath = Array();
foreach($response as $element){
$haasfilepath << $element[key];
}
The foreach will allow you to loop through all the objects returned in response. Within the loop you then push each [Key] into the array that is $haasfilepath. You now have a variable with an array of all key's returned.
As far as I understand, the response will be an XML file (not an array-name-value-pair) and you have to parse the XML file. Try researching xpath and similar methods in parse XMl file in php.
foreach ($response->body as $key => $haasfilepath)
{
echo 'value for key ', $key, ' is ', $haasfilepath, '<br>';
}
or, if you only need the key "key":
$haasfilepath = $response->body['key'];
echo $haasfilepath;

Categories