MongoDB unexpected query result - php

So I'm learning MongoDB and everything was working fine until I wanted to query and discovered that it returns an array that does not work the way I'm used to. Take the example:
$cursor = $collection->find(array('game' => 'Borderlands 2'));
$array = iterator_to_array($cursor);
So far so good, but then I wanted to get a single value to add dynamically to a page:
The game is: <?php echo $array['game'] ?>
And only errors followed. I tried tons of things but then I var_dump it and found that the array is contained under a ID/index array, so this worked:
<?php echo $array["5138225097777c4014000001"]["game"] ?>
I couldn't find any explanation around. Though I understand now how it works, I'm not sure if this is a mistake I made when adding the values to the collection or if I'm missing something. Thanks!!

This is because find returns an array of results(and each result is converted to an array). Hence you have an array of results with the Mongo ObjectId as the key in the array. Use findOne if you want to get just one result.

$cursor = $collection->find(array('game' => 'Borderlands 2'));
while ($document = $cursor->getNext()){
echo $document['game'];
}

Related

Cannot access PHP Object as Array

I am facing a strange problem. It may just be a silly mistake, and I am just missing some basics.
I'm running php 5.6.1 on MAMP.
I have a simple array which I get from a mysql query. Using a foreach loop, I can print_r() each value, which gives me: stdClass Object ( [srno] => 6 [link] => this-is-link )
Now I can echo $obj->srno, and that prints fine. But I can't use echo $obj['srno'] which I was previously using, on an older version of PHP, but- It shows nothing.
Any help really appreciated. Thanks!
If you have a stdClass object and need to address it as an array, you can cast it to array quite easily:
$someObj = new stdClass();
$someObj->foo = "bar";
$someArray = (array)$someObj; // Cast the object to an array
echo $someArray['foo']; // Will give you "bar"
Working example: http://3v4l.org/nni1Y
Of course as comments already pointed out, you may want to look at retrieving your mysql results as an array in the first place.
As you said your results return as an object so you can use it by using
$obj->your_field_name to display field value. But your can not use by $obj['field_name'];

Return Array Element without Creating Variable

I feel stupid for asking this cause it seems so basic but it's really bugging me.
I have a method that returns an array with a single element. I just want it to return the element not wrapped in an array. I tried this.
return $f->getValue()[0];
and it gives an error but if I save it to a variable, it works fine.
$v = $f->getValue();
return $v[0];
I can't figure it out....
It's available only since PHP 5.4: http://codepad.viper-7.com/VHOW0o
What you are trying to do, is called array dereferencing, and is only possible in PHP as of version 5.4 (if you scroll up a few lines in the documentation article I linked to, you'll see it mentioned).
Use reset().
<?php return reset( $f->getValue() ); ?>
Edit: reset() is probably superior to current() as it also makes sure that the internal pointer is reset, despite it not making much difference if the array only contains one element.
As far as I know since you are returning an array you only can get an array. You can instead save the array to a variable in the class (accessible by $f->myArray) and then return just the string portion. Or the other option is to do what your second example is and return the array and retrieve the string from it.
have you tried this
<?php
return array_shift(array_values($array));
?>
Get the first element of an array

How to merge some static data with json encode mysql array data?

I am trying to merge a static data with json encode array data for output. Here is my php code:
$arr = array();
$rs = mysql_query("SELECT id, name, picture, mail, gender, birthday FROM users WHERE id='$logged_id' ");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":'.json_encode($arr).'}';
Now I want to merge other data with it:
$user_ip = array("user_ip" => $user_ip_address);
I have tried array_merge($arr, $user_ip). But it didn't work. I think this is not correct json array format if I merge with existing data array. Please let me know what to do how to output other data as well as current data coming from mysql with json encode.
I am getting such output with my existing code, which is correct:
{"users":[{"id":"14","name":"Sonu Roy","picture":"image012.jpg","mail":"myemail#gmail.com","gender":"Male","birthday":"1983-01-11"}]}
But now I want to add other variable e.g $user_ip_address as user's data joining with current output data like this:
{"users":[{"id":"14","name":"Sonu Roy","picture":"image012.jpg","mail":"myemail#gmail.com","gender":"Male","birthday":"1983-01-11",user_ip:"127.0.0.1"}]}.
I want to get it in this way. How to do it? Please let me know. Thanks in advance.
try this:
echo json_encode(array('users' => $arr, 'user_ip' => $user_ip_address));
on a side note:
you should use PHP PDO class to connect and query the database.
mysql_fetch_object returns an object, not an array. So, what are you doing by $arr[] = $obj; is just adding an object into an array. So, the actual structure of the $arr is something like
$arr => [
[0] => Object(....),
[1] => Object(....),
....
]
In your particular case, I assume you are fetching single row by primary key, so there are only one object.
THe simpliest way to fix this is to add a field to an object. I haven't worked with PHP since 5.3, so can't be sure, but it's as simple as adding
$obj->user_ip = $user_ip_address;
inside the loop.
Btw, a couple of questions for you:
Why do you use loop if it should result in a single row?
Why you are embedding the variable directly into SQL query. It's quite vulnerable, read about sql-injections and how to prevent it (one day I was really tired telling people here on SO to use PDO and prepared statements, so just go read about it),
Have you read the documentation about mysql_fetch_object and array_merge? Why not (because if you have read it you wouldn't be asking the question).
Tried debugging? E.g. attaching a debugger and watching for variables contents? Inserting logging or (God forgive me) debug print with echo?
"Didn't work" is a quite bad error description. This time you was lucky, because the error was obvious. Next time, please, be more specific.

Cannot access elements within an array

I am trying to access elements within an associative array. However, I do not seem to be able to get to the elements. If I use print_r() it says that is IS an array and shows me what is contained within it. However, is_array() returns false. Furthermore, when I echo the first element in the array it returns a value of 'a' rather than the actual array value. This is probably just some stupid mistake, but it is baffling me. Does anyone have any idea what the problem is here?
Thanks in advance for the help.
$sc2 = new ServiceCall($uri,null,false,false);
$sc2->makeCall();
$response = json_decode($sc2->getResponse(),true);
$tmp4 = var_export($response, true);
print_r($tmp4);
if(is_array($tmp4))
echo "Tmp4 is an array";
else
echo "Tmp4 is NOT an array";
var_export() is meant for persisting variables e.g. to files, thus it returns a string.
You can just use $response as your array, not $tmp4.

Filter Mongo cursor fields to desired array index with PHP

In the process of learning to use Mongo and PHP, and got stuck with this.
I have a collection in Mongo with the following structure:
array(3){
["timehack"]=>int(..),
["_id"]=>object..,
["series"]=>
array(3){
[0]=>int(..),
[1]=>int(..),
[2]=>int(..)
}
}
I am trying to query the collection so i get all of the samples with first item in "series", something like:
$cursor = $collection->find();
$cursor->fields(array=>("timehack"=>true, "_id"=>false, "series.0"=>true));
$arr = $cursor->getNext();
var_dump($arr);
The resulting series array is empty. How can I get just the desired index? (I realize that I can get all samples in the series then filter with code, but I would like to know how to accomplish this with a query). Thanks.
In the comments above you have already confirmed that this works with the $slice operator in the shell. So, to give you an example of how $slice works in PHP, I refer you to none other than the PHP tests in the driver itself.
Take a look at line 33 in the tests/MongoCollectionTest2.php file on github:
https://github.com/mongodb/mongo-php-driver/blob/master/tests/MongoCollectionTest2.php
The code goes like this:
$m = new Mongo();
$db = new MongoDB($m, "phpunit");
$this->object = $db->selectCollection('c');
...
...
$results = $this->object->find(array(),array("x" => array('$slice' => 3)))->getNext();
It looks a little convoluted compared to the shell with a lot of casting as an object going on (if I am reading that right), but hopefully enough to get you started :)

Categories