How to get a single value from MongoDB using PHP? - php

So I have the following code to get a document from a collection in my database:
$manager = new MongoDB\Driver\Manager('mongodb+srv://<username>:<password>#cluster0.hyqa4.mongodb.net/academic?retryWrites=true&w=majority');
$filter = ['username' => $uname];
$options = ['projection' => ['_id' => 0]];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery("academic.users", $query);
foreach($cursor as $document) {
print_r($document);
}
I'm able to successfully retrieve a document by searching for the username, so if $uname is "Jon", I get the following output:
stdClass Object ( [username] => Jon [email] => Jon#mail.com [passwd] => pass123 )
However, what I want to do is just return a single value from the document, so if I wanted to get the value for email, it would return:
Jon#mail.com
...so then I could store that value as a variable.
How would I do this?

Std class objects can be accessed via -> operator. So you can user $document->email to access individual email. Is this what you are looking for
$manager = new MongoDB\Driver\Manager('mongodb+srv://<username>:<password>#cluster0.hyqa4.mongodb.net/academic?retryWrites=true&w=majority');
$filter = ['username' => $uname];
$options = ['projection' => ['_id' => 0]];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery("academic.users", $query);
foreach($cursor as $document) {
print_r($document->email);
}

Related

Use a generated string for an array in MySQL with variables

I need to use a generated string as an array within a MySQL-Loop.
The string/array is built into $argumentarray from the $rows arguments and should after be used as the array of multiSQLarray[]
The function is called as:
multiSQL('**id,title,description,link**','menu')
The string gets correctly generated as
array('id' => $result['id'],'title' => $result['title'],'description' => $result['description'], 'link' => $result['link'])
But instead of using it as a string for the array it just adds it to the array for every result from the sql
Array ( [0] => array('id' => $result['id'],'title' => $result['title'],'description' => $result['description'], 'link' => $result['link']) [1] => array('id' => $result['id'],'title' => $result['title'],'description' => $result['description'], 'link' => $result['link']) )
What i expect is the SQL result as the array
Array ( [0] => Array ( [id] => 1 [title] => Customers [description] => Display the Customer Dashboard [link] => index.php ) [1] => Array ( [id] => 2 [title] => Server [description] => Display all Servers [link] => servers.php ) )
My code:
function multiSQL($rows=null,$table=null,$select=null) {
if(is_null($select)) {$filter="";} else { $filter = ' where '.$select; }
global $pdo;
$sql = 'SELECT '.$rows.' FROM '.$table.$filter.'';
$connection =$pdo->prepare($sql);
$connection->execute();
$multiSQLarray = array();
$arguments = explode(',',$rows);
$argumentarray = "";
$argumentscount=count($arguments);
$loopcount = 1;
foreach($arguments as $argument){
if($loopcount==$argumentscount){
$loopcount++;
$argumentarray = $argumentarray.' \''.$argument.'\' => $result[\''.$argument.'\']';
}
else{
$loopcount++;
$argumentarray = $argumentarray.'\''.$argument.'\' => $result[\''.$argument.'\'],';
}
}
$argumentarray = 'array('.$argumentarray.')';
echo $argumentarray.'<br><br>';
while ($result = $connection->fetch(PDO::FETCH_BOTH)) {
//$multiSQLarray[] = array('id' => $result['id'], 'title' => $result['title'], 'description' => $result['description'], 'link' => $result['link']);
$multiSQLarray[] = $argumentarray;
}
print_r($multiSQLarray);
return $multiSQLarray;
Structured data is structured data. Be it in a string or an array. I can't make sense of some of your code. The arrays in strings... unless you are angling to use an eval. I think that bit confuses your question some.
One thing you need to consider is how exposed you will be to SQL injection. Basically never trust the user right? So, you could do things like predfine, in code, the allowed columns. If the form submitted references something not whitelisted then stop! Also, have to think about escaping the user supplied values.
I'd want my function to accept a known, arguments that make sense for what it needs passed in... Clean things up first and then pass some data types that make the most sense to the function. Maybe something like...
/**
* #param string $table
* #param array $fields
* #param array $criteria (key/value pairs where key is field and value is scalar)
*/
function buildQuery($table, $fields, $criteria) {
$where = [];
$whereVals = [];
foreach($criteria as $k => $v) {
$where[] = "({$k} = ?)";
$whereVals[] = $v;
}
$where = implode(' AND ', $where);
$fields = implode(', ', $fields);
$sql = "SELECT {$fields} FROM {$table} WHERE {$where}";
//eg. SELECT id, name, bar FROM fooTable WHERE (id = ?) AND (name = ?)
$query = $pdo->prepare($sql);
$retval = $query->execute($whereVals);
return $retval;
}
$response = buildQuery( 'fooTable',
['id', 'name', 'bar'],
[
'id' => 5,
'name' => 'john'
]);
Maybe look at some frameworks or an ORM like Doctrine? Can see some good examples of OOP representations of a select statement. Makes dynamic query building a lot easier. End up with something DRYer too.

Using Regex in new MongoDB library for PHP7/HHVM

Trying to figure out how to use Regex in new MongoDB library
I didn't find real world example of usage MongoDB\BSON\Regex so I come up with the code below:
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['word' => ['word' => 'heelo']]);
$bulk->insert(['word' => ['word' => 'hello']]);
$manager->executeBulkWrite('db.collection', $bulk);
$filter = ['word' => ['word' => new MongoDB\BSON\Regex("hello","i")]];
$query = new MongoDB\Driver\Query($filter);
$cursor = $manager->executeQuery('db.collection', $query);
foreach ($cursor as $document) {
var_dump($document);
}
But it shows nothing. Does anyone know how to use it?
I've found the answer. I should write query like:
$filter = ['word.word' => new MongoDB\BSON\Regex("hello","i")];

Mongodb $nin php Not Working

This shows me everything (including 55d9d86746ba9a3a7f642b83).
I don't want it to show me the data in the array $veri.
$veri=Array
(
[0] => 55d9d86746ba9a3a7f642b83
)
$urun = $c->find(array('_id' => array('$nin' => $veri)));
Try the below code:
<?php
$mongo = new Mongo();
$db = $mongo->selectDB("foo");
$cur = $db->bar;
$veri = array(
new MongoId('55d9d86746ba9a3a7f642b83')
);
$urun = $cur->find(array('_id' => array('$nin' => $veri)));
foreach($urun as $doc) {
var_dump($doc);
}
?>
Notice how I use MongoId, instead of just copy pasting the id as is. Also notice that the array doesn't need an index [0]

Retrieve fields of Mongo collection in PHP

I tried using the fields() method on the cursor:
<?php
$mongo = new Mongo("mongodb://localhost");
print_r($mongo);
$db = $mongo->test;
// access collection
$collection = $db->test;
// execute query
// retrieve all documents
print_r($test);
$cursor = $collection->find();
print_r($cursor);
$fields = $cursor->fields(array("summary" => true));
print_r($fields);
The output is:
Mongo Object ( [connected] => 1 [status] => [server:protected] => [persistent:protected] => )
MongoCursor Object ( )
MongoCursor Object ( )
Looks like the driver and the connection work but I can't retrieve the distinct summarization of the fields.
Assume that we have access to mongodb database with the name db, are going to retrieve data from MyCollection and use MongoDB\Driver\Manager:
$manager = new MongoDB\Driver\Manager( $DB_CONNECTION_STRING );
Then we retrieve data in this case by name with a limit 2 documents and want to get only fields name, age and address among many others. Projection option can be used to specify which fields should be returned using 0 to exclude and 1 to include:
$filter = ['name' => 'John'];
$options = [ 'projection' => ['_id' => 0, 'name' => 1, 'age' => 1, 'address' => 1], 'limit' => 2 ];
$query = new MongoDB\Driver\Query($filter, $options);
$manager->executeQuery('db.MyCollection', $query);
If we need to get all columns, then we simply omit projection option at all as the following:
$filter = ['name' => 'daniel'];
$options = [];
$query = new MongoDB\Driver\Query($filter, $options);
$manager->executeQuery('db.MyCollection', $query);
const HOST = 'localhost';
const PORT = 27017;
const DBNAME = 'test';
const COLLECTION = 'test';
$connectionString = sprintf('mongodb://%s:%d', HOST, PORT);
try {
$connection = new Mongo($connectionString);
$database = $connection->selectDB(DBNAME);
} catch (MongoConnectionException $e) {
throw $e;
}
$collection = $database->selectCollection(COLLECTION);
try{
$query = array();
$specifyKey = array("summary" => true);
$cursor = $collection->find($query , $specifyKey);
}catch(MongoException $e) {
die('Failed to find One data '.$e->getMessage());
}catch (MongoCursorException $e) {
echo "error message: ".$e->getMessage()."\n";
echo "error code: ".$e->getCode()."\n";
}
while ($cursor->hasNext()){
$nextCursor = $cursor->getNext();
//process next cursor
}
After the $cursor variable try an foreach instead. It goes through the cursor results.
foreach($cursor as $document) {
var_dump($document);
}

About creating an array at php

I am having trouble at creating a specific array.
What i want is to pull the info for my members (from mysql database) and then store them to an array.
The array should be like this:
$members = array(
'John' => array('avatar' => '/images/avatar/ji.jpg', 'country' => 'uk.'),
'Nick' => array('avatar' => '/images/avatar/nick.jpg', 'country' => 'italy.'),
);
etc..
so i pull the name,avatar url and country from the db and then i store them in to the previous array.
My question is, how could i create this array?
Thanks in advance!
About creating an array at php.
Something like this should work:
$members = array();
$q = mysql_query("SELECT name , avatar, country from table");
while($row = mysql_fetch_assoc($q)){
$array = array("avatar" => $row['avatar'] , "country" => $row['country']);
$members[$row['name']] = $array;
}
Using PDO:
$members = array();
$conn = new PDO("mysql:host=$host;dbname=$database", $username, $password);
$sql = "SELECT name, avatar, country FROM members";
foreach ($conn->query($sql) as $row) {
$temp = array('avatar' => $row['avatar'], 'country' => $row['country']);
$members[$row['name']] = $temp;
}

Categories