mongo count(*) with php but without sending all result array - php

I am writing my scripts in PHP and I try to convert SQL
SELECT COUNT(*) AS Rank
FROM user
WHERE user.lvl > $user_level
query to Mongo.
I found only one decision:
$nosql = array(
'lvl' => array('$gt' => $user_level)
);
$result = $collection->find($nosql);
$length = count(iterator_to_array($result));
get all objects which satisfy the condition
And count them in PHP
It is possible to get count of needed objects without sending all array?

mongodb can count result like this you didn't need to use count(iterator_to_array($result));
$nosql = array(
'lvl' => array('$gt' => $user_level)
);
$result = $collection->find($nosql);
$length = $result->count();

The new driver does not implement $cursor->count() use $collection->count() instead
$collection->count($filter)

Related

Like queries in MongoDb Using PHP

I want to use like queries for search in my app using MongoDb With PHP but I did not get the proper result.
Code:
$query = array("first_name" => "/.*a.*/" );
$updateResult = $this->dbCustomer->find($query);
Try this,
$query = array("first_name" => array("$regex" => "/.a./"));
$updateResult = $this->dbCustomer->find($query);
more details, please check this out
I got an answer and I try this and it's work perfect :
$query = array(array("first_name" => new MongoDB\BSON\Regex("$search_text", 'i')))

projection with array in php mongodb

I have a collection with entries like:
"Name":"test",
"Description":"some desc here",
"Teams":[0:"idhash1",1:"idhash2"],
"clientId":"clienthash"
from which I return all items like this:
$filter = array('clientId' => $clientID);
$options = [];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $this->conn->executeQuery('dbname.collectionname', $query);
Now I want to add another filter on team value:
$filter = array('clientId' => $clientID,'Teams'=>'idhash1');
$options = [];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $this->conn->executeQuery('dbname.collectionname', $query);
which obviously doesn't work. How would I get this to work? I am on PHP7.0, MongoDB 4.0 and extension version 1.4.2
This would be helpful
$insert in MongoDB with Php
http://php.net/manual/en/mongocollection.insert.php
What I decided to do was add the teamid's not only in an array but also as separate keys:
"Name":"test",
"Description":"some desc here",
"Teams":[0:"idhash1",1:"idhash2"],
"clientId":"clienthash",
"Team_idhash1":1,
"Team_idhash2":1
Making querying them very easy and it performs a lot better this way filtering on a team.

How to generate a JSON objet in PHP with two arrays inside

I´m trying to create my own leaderboards sytem for my games so I´m working with PHP and requesting info with Ajax into the games, but as I´m not good at all with PHP I´m pretty confused about how to create a JSON object with all the info I need to handle in the javascript part.
What I want to do, in the PHP part is to generate this JSON object:
{players: ["name1", "name2", ..., "name10"], scores:[score1, score2, ..., score10]}
So I can work in javascript with something like
dataReceived.players[0]
I´m storing and getting the data correctly from the database but I´m not being able to generate that JSON object to receive in the Ajax request. Basically, this is my PHP code:
$query = "SELECT * FROM leadersboards ORDER by score ASC LIMIT 10";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$result_length = mysql_num_rows($result);
$arrayScores = array();
$arrayPlayers = array();
for($i = 0; $i < $result_length; $i++){
$row = mysql_fetch_array($result);
array_push($arrayPlayers, $row['player']);
array_push($arrayScores, $row['score']);
}
$answer = json_encode(array('item' => $arrayPlayers, 'item' => $arrayScores), JSON_FORCE_OBJECT);
Sorry if I made something stupid in PHP, as I said, I don´t know PHP at all, just pretty basic stuff.
The problem is:
array('item' => $arrayPlayers, 'item' => $arrayScores)
You are overwriting the item key right after you set it.
I think you want to do something like this
$answer = json_encode(array('players' => $arrayPlayers, 'scores' => $arrayScores)
Ok, so I fixed it this way, I don´t know if is the best option but it works
$myObject = new stdClass();
$myObject = array(
"players" => $arrayPlayers,
"scores" => $arrayScores,
);
echo json_encode($myObject);
Please stop using mysql_* instead use mysqli_* or PDO.
As per your expected out put of arrays inside object use the below code:
$answer = json_encode(array('players', 'scores'));
$answer->players = $arrayPlayers;
$answer->scores= $arrayScores;

ZF2 - bind array to single database query parameter

I'm trying to run a simple query against a Zend\Db\Adapter\Adapter instance. Some sample code:
$sql = "DELETE FROM Goals WHERE match_no = ? AND event_id NOT IN (?) ";
$res = $this->adapter->query($sql, array($matchNo, $goalIds));
return $res->getAffectedRows();
This won't work unfortunately, as the array $goalIds isn't quoted as a list for the IN () part of the SQL, but instead is placed in the SQL as 'Array'.
I've searched and search, and also played with the ZF2 ParameterContainer, but can't work out how to quote an array into a single parameter of comma separated values like this.
I'm pretty sure this could work if I used DB Select functionality, but I'd rather just keep to plain old SQL and parameter for these type of quick queries.
Any help much appreciated.
:wq
Assuming you are using MySQl Adapter, You can do things in the Zend way by writing this:-
use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Sql;
use Zend\Debug\Debug;
$config = array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=database;host=localhost;charset=utf8',
'user' => 'root',
'pass' => 'password',
);
$adapter= new Adapter($config);
$sql = new Sql($adapter);
$select = $sql->select();
$select->from('Goals');
$select->where->notin('match_no', array($matchNo, $goalIds));
$select->where->notin('event_id', array($matchNo, $goalIds));
$selectString = $sql->getSqlStringForSqlObject($select);
$results = $adapter->query($selectString, $adapter::QUERY_MODE_EXECUTE);
Debug::dump($results);

Query in zend framework returns empty array

i am running a custom query, no models involved, and it return an empty array.
Here is exact code that i use:
$query = 'SELECT SUM(open_diff) opens, SUM(revenue_diff) revenue, SUM(revenue) real_rev, manual_rev, SUM(opens) actual_opens
FROM data.discrepancy
WHERE discrepancy_date >= \''.$dateStart.'\' AND discrepancy_date <= \''.$dateEnd.'\' AND feed_id = '.$feeds[$i]["feed_id"];
$db = Zend_Registry::get('db_slave');
$stmt = $db->query($query);
$records = $stmt->fetchAll();
Zend_Debug::dump($records); gets me this result:
array(1) {
[0] => array(5) {
["opens"] => NULL
["revenue"] => NULL
["real_rev"] => NULL
["manual_rev"] => NULL
["actual_opens"] => NULL
}
}
The data is in the database, and if i run that query directly in MySql, i have no problems.
Please advise.
MySQL will return null for sum() if there are no matching records. What is the final query being executed (with the variables evaluated)?
I'd try running that in MySQL directly as well and you'll probably get the same results.
var_dump($dateStart, $dateEnd, $feeds[$i]['feed_id']);
See what those contain and you'll probably see the problem.
Try following code
$dbAbstract = new Zend_Db_Table_Abstract();
$select = $dbAbstract->select()
->from(
array('a' => 'data.discrepancy'),
array('SUM(open_diff) AS opens', 'SUM(revenue_diff) AS revenue'), 'SUM(revenue) AS real_rev', 'SUM(opens) AS actual_opens'
)
->where('discrepancy_date >=?', $dateStart)
->where('discrepancy_date <=?', $dateEnd)
->where('feed_id =?', $feeds[$i]["feed_id"]);
$result = $dbAbstract->fetchAll($select);
Please remove AS that is not working

Categories