PHP MongoDB find query - php

I try use this solution for pagination in PHP:
public function getRecords($page, $count, $currentId)
{
$query = ["_id" => ['$gt' => $currentId]]; //what's wrong here?
$cursor = $this->recordsCollection->find($query)->
skip(($page-1) * $count)->
limit($count)->
sort(["_id" => true]);
$result = array();
foreach ($cursor as $doc) {
array_push($result, $doc);
}
return $result;
}
But it returns an empty array result. Also I tried this query without skip and limit, but the result still was an empty array. If $query is empty, everything is ok, it returns all records in colection.
What I'm doing wrong?
SOLUTION$query = ["_id" => ['$gt' => new MongoId($currentId)]];

Maybe $currentId is of wrong type? Looking at what you're trying to do I think it should be instance of MongoId

Related

Loop parameters through a query collection and then merge them (Laravel 8)

I got a few parameters in the url that I want to loop into a Laravel where query. After doing that I want to merge them into 1 collection and without duplicates.
This is what I have written already:
foreach($request->query() as $key => $query){
$guides[] = SupportGuideTranslation::where($key, $query)->get();
}
These are my parameters:
?active=1&language_id=2
Your current code executes one query per parameter/condition. You could do:
$query = SupportGuideTranslation::query();
foreach($request->query() as $key => $value){
$query->where($key, $value);
}
$guides = $query->get();
I would also advise you to check that the parameter actually exists on the table before adding it to the query. If I make a request with active=1&non_existing_column=2 your code would throw an error.
$guides = new Collection;
foreach($request->query() as $key => $value){
if($guides->isEmpty()){
$guides = SupportGuideTranslation::where($key, $value)->get();
}
else{
$guides = $guides->toBase()->merge(SupportGuideTranslation::where($key, $value)->get());
}
}
$guides = $guides->unique();
where() can take an array. So you don't necessarily need to loop:
SupportGuideTranslation::where($request->query())->get();
If that doesn't work for you and you have to loop over the query params, that might help:
$guides = new Collection;
foreach($request->query() as $key => $query){
$guides = $guides->merge(SupportGuideTranslation::where($key, $query)->get());
}
$guides = $guides->unique();

how to select specific records from mongodb using php

I am using the following code:
foreach ($record as $doc)
{
$groupIds[] = $doc['groupId'];
}
$gpids = "'".implode("','",array_unique($groupIds))."'";
$collection5 = $db->chat;
$cursor = $collection5->find(array('groupId' => array('$in' => array($gpids))));
foreach($cursor as $res)
{
print_r($res);
}
but no results will come. Please help me.
That is because your $gpids is a string and you end up putting one element array in the $in query. This should work:
$collection5->find(array('groupId' => array('$in' => array_unique($groupIds))));

Class Function does not return array properly

I can't seem to get the array to return from the function correctly, every time I run the script it just echoes out 0, even though I have checked that the MySQL query returned at least 1 row. I've also tried using $_GLOBALS["FORUM_ANSWERS"][] = ..., however it still did not work.
public function getAnswers() {
$dbh = $this->dbh;
$id = $this->question_id;
$q = $dbh->prepare("SELECT * FROM answers WHERE question_id = :id");
$q->bindParam(":id", $id);
$q->execute();
$nr = $q->rowCount();
if ($nr == 0) {
echo "No Questions";
}
$_GLOBALS["FORUM_ANSWERS"] = [];
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
array_push($_GLOBALS["FORUM_ANSWERS"], array(
"num_id" => $row["num_id"],
"question_id" => $row["question_id"],
"answer" => $row["answer"],
"name" => $row["name"],
"username" => $row["username"],
"ip" => $row["ip"],
"date" => $row["date"],
));
}
return $GLOBALS["FORUM_ANSWERS"];
}
SEPERATE FILE:
$answers = $forum->getAnswers();
echo count($answers);
You are assigning to $_GLOBALS and returning $GLOBAL.
You actually don't need to use a global array by the look of it - I would just assign the array to a variable (that you initialise in the function) and return that.

Find Method Returning False

I am trying to execute a find in my script, but I believe my condition is returning false. I am trying to execute a find and pull all records that match the given value in my $data variable. I have tried to compare the BranchLicense.RegionCode to $data but no luck. I have also tried to compare it the _Session['Auth']['User']['region_code']. The $data variable is returning the correct value but the script does not return the proper records. What am I doing wrong here? Here is my code.
//echo '<pre>'; print_r($_SESSION); echo '</pre>';
//$this->loadModel('AuthAcl.Users');
$data = $_SESSION['Auth']['User']['region_code'];
//$data = $this->Users->find('all');
$new = $this->BranchLicense->find('all', array(
'conditions' => array('BranchLicense.RegionCode' == $data)));
die(debug($new));
$this->layout = 'default';
//$this->set('branchLicenses', $this->BranchLicense->find('all', array(
//'conditions' => array('BranchLicense.RegionCode' === '$data'))));
Try as follows-
$new = $this->BranchLicense->find('all', array(
'conditions' => array('BranchLicense.RegionCode' => $data)));
die(debug($new));

Return a record from PHP with function and render

I have a function
function getUser($linkedInID) {
$sql = "SELECT * FROM ipadapi.users WHERE linkedInID = '".$linkedInID."'";
$results = mysql_query($sql) or die("Error in User SQL query.");
return $results;
}
and this is called via
$returnedUser = getUser($linkedInID);
// Generate the array for the JSON String
$returnedMessage = array(
'status' => 'ok',
'error' => false,
'avatar' => $returnedUser['avatar'],
'userSelectedTheme' => $returnedUser['userSelectedTheme'],
'checksum' => $checksum
);
// JSONify the string and return it
$returnedJSON = json_encode($returnedMessage);
echo $returnedJSON;
However the results of $returnedUser['(field name']Althought, are always coming up NULL. avatar, userSelectedTheme are some of the fields from the dbase. I have confirmed in the database the infomation is there
I suspect I am missing a key line from my function which involves =array() somewhere and manflu is preventing me seeing it.
Any advice greatly appreicated
First of all stop using mysql_(Why shouldn't I use mysql_* functions in PHP?) is deprecated.
mysql_query from getUser function returns a resource. you must
return an array. so have a look at mysql_fetch_array or mysql_fetch_assoc functions
basically you must return mysql_fetch_array($results) assuming that is only one result comming from db. otherwise you'll have to loop through them.
Thanks to all those who answered, and extra plaudits to those who spotted the use of the depreciated mysql commands.
Had a shot of espresso and got the answer working (albeit unsafe and unsecure and..)
function getUser($linkedInID) {
$sql = "SELECT * FROM ipadapi.users WHERE linkedInID = '".$linkedInID."'";
$results = mysql_query($sql) or die("Error in User SQL query.");
$arr = array();
while($row= mysql_fetch_assoc($results)){
$arr['avatar'] = $row['avatar'];
$arr['userSelectedIndustry'] = $row['userSelectedIndustry'];
}
return $arr;
}
and the call
$returnedUser = array();
$linkedInID = filter_var($_REQUEST['linkedInID'], FILTER_SANITIZE_STRING);
$returnedUser = getUser($linkedInID);
// Generate the array for the JSON String
$returnedMessage = array(
'status' => 'ok',
'error' => false,
'avatar' => $returnedUser['avatar'],
'userLinkedInIndustry' => $userLinkedInIndustry,
'userSelectedTheme' => $returnedUser['userSelectedTheme'],
'userSelectedIndustry' => $returnedUser['userSelectedIndustry'],
'checksum' => $checksum
);
// JSONify the string and return it
$returnedJSON = json_encode($returnedMessage);
echo $returnedJSON;
many thanks for all time spent, and apologies for not just getting my head down and figuring it out
$data=array();
while($row=$result->fetch_array(MYSQLI_ASSOC))
{
data[]=$row;
}
return $row;

Categories