How to get entire MongoDB collection with PHP - php

Using the following code, I can grab a node from a collection:
<?php
$user = "xxxx";
$pwd = 'xxxx';
if (isset($_POST['needleID'])) {
$needleID = $_POST['needleID'];
} else {
echo "needle ID not set";
}
//Manager Class
$connection = new MongoDB\Driver\Manager("mongodb://${user}:${pwd}#localhost:27017");
// Query Class
$filter = ['id'=> $needleID];
$query = new MongoDB\Driver\Query($filter);
// Output of the executeQuery will be object of MongoDB\Driver\Cursor class
$rows = $connection->executeQuery('DBNAME.DBCOLLECTION', $query);
// Convert rows to Array and send result back to javascript as json
$rowsArr = $rows->toArray();
echo json_encode($rowsArr);
?>
However, what I'm really looking to do is get everything from the DBCOLLECTION.
I'm kind of at a loss on how to do this. A few searches either go over my head or are for older versions of the PHP driver, such as this one fetch all data from mongodb collection

If you query on a specific ID, then you will only receive the document with that ID as its value. If you want to retrieve all document in a collection, leave the filter empty, i.e. with $filter = [];.

It is better to use mongoexport for exporting collections. On large collections your code will be slow and will timeout. Consider using pagination for results.

Related

How to export data from user modx database to form?

I've table in modx database (orders), and i need to export data from that db to table at site.
I pushing into db with following snipept
<?php
function agregarCargas( &$fields )
{
global $modx;
// Init our array
$dbTable = array();
$dbTable['subject'] = $modx->db->escape($fields['subject']);
$dbTable['fullname'] = $modx->db->escape($fields['fullname']);
$dbTable['message'] = $modx->db->escape($fields['message']);
// Run the db insert query
$dbQuery = $modx->db->insert($dbTable, 'orders' );
return true;
}
?>
How can i export from DB? Snippet or? Thanks.
(Old thread, just for new folks trying to tackle this...)
Looking at the API you're using I'm guessing you are stuck with an old MODx version. (Evolution)
You should take a look at the API::DB docs for MODX Evolution
Something along the lines of the following would fill your HTML table:
$res = $modx->db->select("subject, fullname", 'orders');
$res_rows = $modx->db->makeArray($res);
$rows = "";
for($n=0;$n<count($res_rows);$n++){
$rows .= "<tr><td>".$res_rows['subject']."</td><td>".$res_rows['fullname']."</td></tr>\n";
}
return $rows;
(Of course you should use chunks instead of hardcoded HTML)

navigating an array of objects in javascript

Need help forming javascript objects from MySQL rows of data. I'm using IE9 and Chrome on Windows-7.
I've managed to get what I believe to be an array (of objects) in Javascript from mySQL data. I can use alerts to see the whole array, as well as one individual object, as in my code.
What I cannot do yet is navigate a particular object's properties (the column values of a particular row in the database).
What I need to do is iterate through myObjects, and use the property values in each to create some graphics. I also need to be able to retrieve each object's properties at any time going forward as well.
UPDATE: including my php located in head html object:
<?php
//------------------- constants --------------------
$objects = array();
$jsonData = "";
//------------------- database connection ----------
$data_source = 'mysql:host=localhost;dbname=myDB';
$db_user = 'root';
$db_password = 'password';
$conn = new PDO($data_source, $db_user, $db_password,
array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT));
//prepare query
$stmt = $conn->prepare("SELECT * FROM tblbranchstatus");
$stmt->execute();
//fetch each row of results
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$rows[] = json_encode($row);
}
?>
var ART = {};
//capture data from database as json string data
ART.strJSON = <? php echo json_encode($rows); ?> ;
//capture json string data as array of javascript objects
//using 'eval' cause I know this data's source and I couldn't get JSON.parse to work
ART.myObjects = eval(ART.strJSON);
ART.branch = ART.myObjects[6];
alert(ART.branch); // this gives me the expected object {"a":"aa", "b":"bb"...}
alert(ART.branch.a); // can't retrieve the property - gives me 'undefined'
This doesn't look like the right thing to do. Here's what you should be doing:
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$rows[] = $row;
}
Don't do json_encode() on each row.
ART.myObjects = <?php echo json_encode($rows); ?>;
You can immediately use the output of json_encode($rows) in your script.
Update
As rightfully mentioned by bfavaretto, you can make this even shorter by encoding all rows in one go:
ART.myObjects = <?php echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC)); ?>;
I would check if ART.branch is actually a string with the JSON notation rather than the actual object.

convert mysql query in to an array format

can any one know the, convert mysql query in to an php array:
this is mysql query :
SELECT SUM(time_spent) AS sumtime, title, url
FROM library
WHERE delete_status = 0
GROUP BY url_id
ORDER BY sumtime DESC
I want to convert this query in to simple php array .
So, you need to get data out of MySQL. The best way, hands down, to fetch data from MySQL using PHP is PDO, a cross-database access interface.
So, first let's connect.
// Let's make sure that any errors cause an Exception.
// <http://www.php.net/manual/en/pdo.error-handling.php>
PDO::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// We need some credentials...
$user = 'username';
$pass = 'password';
$host = 'hostname';
$dbname = 'database';
// PDO wants a "data source name," made up of those credentials.
// <http://www.php.net/manual/en/ref.pdo-mysql.connection.php>
$dsn = "mysql:host={$host};dbname={$dbname}";
$pdo = new PDO($dsn, $user, $pass);
There, we've connected. Let's pretend that $sql has the SQL you provided in your question. Let's run the SQL:
$statement = $pdo->prepare($sql);
$statement->execute();
There, it's been executed. Let's talk about results. You steadfastly refuse to tell us how you want your data structured, so let's go through four ways that you could get your data.
Let's first assume that the query returns a single row. If you want a numerically indexed array, you would do this:
// <http://www.php.net/manual/en/pdostatement.fetch.php>
$array = $statement->fetch(PDO::FETCH_NUM);
unset($statement);
If you want an associative array with the column names as the keys, you would do this:
$array = $statement->fetch(PDO::FETCH_ASSOC);
unset($statement);
Now, what if the query returns more than one record? If we want each row in a numerically indexed array, with each row as an associative array, we would do this:
// <http://www.php.net/manual/en/pdostatement.fetchall.php>
$array = $statement->fetchAll(PDO::FETCH_ASSOC);
unset($statement);
What if we want each row as a numerically indexed array instead? Can you guess?
$array = $statement->fetchAll(PDO::FETCH_NUM);
unset($statement);
Tada. You now know how to query MySQL using the modern PDO interface and get your results as no less than four types of array. There's a tremendous number of other cool things that you can do in PDO with very minimal effort. Just follow the links to the manual pages, which I have quite intentionally not linked for you.
This over-the-top post has been brought to you by the letters T, F and W, and the number PHP_MAX_INT + 1.
i don't get you clearly, but
mysql_fetch_array and mysql_fetch_assoc
both returns only array
please refer:-
http://php.net/manual/en/function.mysql-fetch-array.php
http://php.net/manual/en/function.mysql-fetch-assoc.php
If you just need a simple array...
while ($row = mysql_fetch_array($query)) { //you can assume rest of the code, right?
$result[$row['url_id']] = array($row['sumtime']);
}
For a simple array
$sql = mysql_query("SELECT SUM(time_spent) AS sumtime, title, url
FROM library
WHERE delete_status = 0
GROUP BY url_id
ORDER BY sumtime DESC");
while($row = mysql_fetch_array($sql)){
$array1 = $row['sumtime'];
$array2 = $row['title'];
$array3 = $row['url'];
}
Hope this is one you wanted
Dude the fastest way is probably the following
$data = array();
while($row = mysql_fetch_array($result))
{
$data[] = $row;
}
print_r($data);

Is it best to make fewer calls to the database and output the results in an array?

I'm trying to create a more succinct way to make hundreds of db calls. Instead of writing the whole query out every time I wanted to output a single field, I tried to port the code into a class that did all the query work. This is the class I have so far:
class Listing {
/* Connect to the database */
private $mysql;
function __construct() {
$this->mysql = new mysqli(DB_LOC, DB_USER, DB_PASS, DB) or die('Could not connect');
}
function getListingInfo($l_id = "", $category = "", $subcategory = "", $username = "", $status = "active") {
$condition = "`status` = '$status'";
if (!empty($l_id)) $condition .= "AND `L_ID` = '$l_id'";
if (!empty($category)) $condition .= "AND `category` = '$category'";
if (!empty($subcategory)) $condition .= "AND `subcategory` = '$subcategory'";
if (!empty($username)) $condition .= "AND `username` = '$username'";
$result = $this->mysql->query("SELECT * FROM listing WHERE $condition") or die('Error fetching values');
$info = $result->fetch_object() or die('Could not create object');
return $info;
}
}
This makes it easy to access any info I want from a single row.
$listing = new Listing;
echo $listing->getListingInfo('','Books')->title;
This outputs the title of the first listing in the category "Books". But if I want to output the price of that listing, I have to make another call to getListingInfo(). This makes another query on the db and again returns only the first row.
This is much more succinct than writing the entire query each time, but I feel like I may be calling the db too often. Is there a better way to output the data from my class and still be succinct in accessing it (maybe outputting all the rows to an array and returning the array)? If yes, How?
Do you actually have a performance issue?
If your current setup works and doesn't suffer from performance issues, I wouldn't touch it.
This sort of DB access abstraction will likely become a maintenance issue and probably won't help performance.
Also, you're susceptible to SQL injection.
You should be able to store the whole object from the query into a variable and then access the single values from that object:
$object = $listing->getListingInfo('','Books');
$title = $object->title;
$price= $object->price;
But you can also use fetch_assoc() and return the whole assiciative array:
$array = $listing->getListingInfo('','Books');
$title = $object['title'];
$price= $object['price'];
This will give you the same results and also with only one query to the DB.
EDIT: If the getListingInfo() is the only function you should think of the following:
rename the function to prepareListingInfo() and within the function only prepare the query and store it in a class variable.
add a getNextListingInfo() function, which will return an object or associative array with the next row.
Using this new function, you can get every row that matches your query.
Either cache the result in an internal var
Or Comment it with a warning and explain to function users to copy the result in an var instead of calling it again and again with the same params
Yes, that would be calling the db too often.
A couple of solutions
1) put the listing info in a variable
2) cache the results in a hashmap or dictionary (be careful for memory leaks)

PHP mySQL - Can you return an associated array with a number index?

I have this method in my db class
public function query($queryString)
{
if (!$this->_connected) $this->_connectToDb(); //connect to database
$results = mysql_query($queryString, $this->_dbLink) or trigger_error(mysql_error());
return mysql_num_rows($results) > 0 ? mysql_fetch_assoc($results) : false;
}
This works great for queries that return 1 row, but how can I get an array returned something like this?
$array[0]['name'] = 'jim'
$array[0]['id'] = 120
$array[1]['name'] = 'judith'
$array[1]['ID'] = 121
Now I know I could use a while loop to insert this data into the array like so, but I was wondering if PHP could do this with an internal function? I havn't been able to find on the docs what I'm after.
The reason I don't want to run the while within the method is because I am going to reiterate back over the array when it's returned, and I'd rather not run through the results twice (for performance reasons).
Is there a way to do this? Do I have a problem with my general query method design?
Thank you muchly!
public function query($queryString)
{
if (!$this->_connected) $this->_connectToDb(); //connect to database
$results = mysql_query($queryString, $this->_dbLink) or trigger_error(mysql_error());
$data = array();
while($row = mysql_fetch_assoc($results))
{
$data[] = $row;
}
return $data;
}
this will always return an array.
EDIT:
I didn't read the question well.
If you realy don't want to use the loop then I would do this:
public function query($queryString)
{
if (!$this->_connected) $this->_connectToDb(); //connect to database
return mysql_query($queryString, $this->_dbLink) or trigger_error(mysql_error());
}
then loop over it, however I would just use the loop.
You might also want to look at the PDO extension. You can load the entire result set into an array or you can loop using foreach.
<?php
$db = new PDO($connection_string, $username, $password);
$result = $db->query($queryString);
foreach($result as $row) {
// do something
}
// or
$result = $db->query($queryString);
$result_array = $result->fetchAll(PDO::FETCH_ASSOC);
?>
Most people use a while() loop in the query to do exactly what you want and then loop over the array to process it.
However, you're right: it wastes memory, which could be a problem with a large dataset. An alternative is for your query method to return the resultset resource. Then your while loop can use that to fetch each row as it requires it.
To abstract that away, I would suggest another class to do that for you. Then your query call would return a new instance of that class which has the MySQL resultset resource as an instance variable and packages up the mysql_fetch_assoc() call.
Look at PEAR::MDB2 (Quickstart Cheatsheet). It provides lots of different functions for doing something like this. It also does not tie you down into using MySQL specific functions because it is a database abstraction layer.
$result = $db->queryRow($query, MDB2_FETCHMODE_ASSOC);
There are other abstraction layers such as ADO as well.
thanks for the ideas. I have a function that returns an associative array from the sql (used in Moodle).
$results = get_records_sql($sql);
//to create a numerically indexed array:
$data = array();
foreach ($results as $row)
{
$data[] = $row;
}
return $data;
}

Categories