I know that the function fetchObject (http://www.php.net/manual/en/pdostatement.fetchobject.php) gives me the next row as an object of the specified class, but I want to get all the rows as an object of the specified class, does PDO has some function to this or I have to do it manually???
THanks!!
You are looking for PDOStatement::fetchAll:
PDOStatement::fetchAll — Returns an array containing all of the result set rows
Example usage:
$arr = $stmt->fetchAll(PDO::FETCH_CLASS, $class_name, $constructor_args);
If you do not need all of the objects in a single array, you will probably find iterating through all the rows to work just as well:
while ($obj = $stmt->fetchObject($class_name, $constructor_args)) {
// Process $obj
}
Related
I got this code from the internet. I don't know how the
$databases = current($res->toArray());
is working in the code. I am new in MongoDB and PHP. How is the current function able to retrieve all values? What exactly is executeCommand retrieving?
$mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$listdatabases = new MongoDB\Driver\Command(["listDatabases" => 1]);
$res = $mng->executeCommand("admin", $listdatabases);
$databases = current($res->toArray());
foreach ($databases->databases as $el) {
echo $el->name . "\n";
}
$res = $mng->executeCommand("admin", $listdatabases); executes the listDatabases command and assigns the result to $res. The result is a Cursor object, which has a toArray method.
The result of some $res->toArray() is, not surprisingly, an array. Its first element is an object that contains the list of databases.
Now, current is not a function specific to MongoDB. It's a standard PHP function that returns the current element of an array. Since the array was just created, the current element is the first element, the object that contains the list of databases.
So $databases = current($res->toArray()); gets you an object ($databases) that has a property databases which contains an array of database objects that you can iterate with foreach.
I have a script that loops through and retrieves some specified values and adds them to a php array. I then have it return the value to this script:
//Returns the php array to loop through
$test_list= $db->DatabaseRequest($testing);
//Loops through the $test_list array and retrieves a row for each value
foreach ($test_list as $id => $test) {
$getList = $db->getTest($test['id']);
$id_export[] = $getList ;
}
print(json_encode($id_export));
This returns a JSON value of:
[[{"id":1,"amount":2,"type":"0"}], [{"id":2,"amount":25,"type":"0"}]]
This is causing problems when I try to parse the data onto my android App. The result needs to be something like this:
[{"id":1,"amount":2,"type":"0"}, {"id":2,"amount":25,"type":"0"}]
I realize that the loop is adding the array into another array. My question is how can I loop through a php array and put or keep all of those values into an array and output them in the JSON format above?
of course I think $getList contains an array you database's columns,
use
$id_export[] = $getList[0]
Maybe can do some checks to verify if your $getList array is effectively 1 size
$db->getTest() seems to be returning an array of a single object, maybe more, which you are then adding to a new array. Try one of the following:
If there will only ever be one row, just get the 0 index (the simplest):
$id_export[] = $db->getTest($test['id'])[0];
Or get the current array item:
$getList = $db->getTest($test['id']);
$id_export[] = current($getList); //optionally reset()
If there may be more than one row, merge them (probably a better and safer idea regardless):
$getList = $db->getTest($test['id']);
$id_export = array_merge((array)$id_export, $getList);
I use this MongoDB library for PHP
If I use this code:
$db->users->find();
I get an associative array.
Is it possible to get an object as a result of find() method?
For example, in PDO I can do it like this:
$stmt->fetch(PDO::FETCH_OBJ);
Thank you.
If all you're looking for is an stdclass object (like with PDO::FETCH_OBJ), you can cast the current element:
$obj = (object) $db->users->find()->getNext();
Learn more about casting in the PHP manual:
Type Juggling (PHP Manual)
The call
$db->users->find();
returns a \MongoCursor object, which is an iterator you can loop over in a foreach loop as you would with an array. But each result you get from it, though, is an associative array.
http://php.net/mongocollection.find
So, to get objects instead you could cast each item to object prior to using it :
$list = $db->users->find();
foreach($list as $user) {
$user = (object)$user; // object cast here
echo $user->name; // use it as an object
}
I'm using this:
$this->getDoctrine()->getRepository('MyBundle:MyEntity')->findAll(array(), Query::HYDRATE_ARRAY);
I thought that should ensure it returns an array of an array, but it still returns an array of objects.
I need the whole result returned as an array of an array so I can do this kind of thing (silly example, but it explains what I mean):
<?php
$result = $this->getDoctrine()->getRepository('MyBundle:MyEntity')->findAll('return-an-array');
?>
This is the age of the person at the 5th record: <?php echo $result[4]['age']; ?>
According to this EntityRepository class, findAll don't take multiple arguments.
The code below should do what you want
$result = $this->getDoctrine()
->getRepository('MyBundle:MyEntity')
->createQueryBuilder('e')
->select('e')
->getQuery()
->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
You can also use the getArrayResult() function instead of getResult(). It returns an array of data instead:
$query = $em->createQuery("SELECT test FROM namespaceTestBundle:Test test");
$tests = $query->getArrayResult();
Use getScalarResult() to get an array result with objects truncated to strings.
There is probably a very simple explanation for this, but I've had this code working for months, and now all of a sudden today it doesn't work.
I retrieve all the rows from a table. I have and object which is an entity model of the table I'm selecting from. As I read the rows from the associative result array, I'm storing each property using "$this->propertyName," and then I'm pushing each object to an array. Before I ended up with an array of objects, now I end up with an array of the same object repeated. Here's a code snippet:
$mdSelectALL_sql="SELECT * FROM member_data";
$mdSelectALL=mysql_query($mdSelectALL_sql,$mdConn);
if(!$mdSelectALL){
die('Error: ' . mysql_error());
}
else{
echo "RETURNING ALL MEMBER DATA RECORDS!!!<br>";
//store all records into array
while($row=mysql_fetch_array($mdSelectALL))
{
$this->mdId=$row['md_id'];
$this->mdFname=$row['md_fname'];
$this->mdLname=$row['md_lname'];
$this->mdEmail=$row['md_email'];
$this->mdTwitter=$row['md_twitter'];
$this->mdFacebook=$row['md_facebook'];
$this->mdMyspace=$row['md_myspace'];
$this->mdPhoneNumber=$row['md_phonenumber'];
$this->mdNotes=$row['md_notes'];
//store records in array
array_push($mdArray,$this);
}//end while
// print_r($mdArray); prints the array and each element is the last record encountered in the SQL retrieval
return $mdArray;
}//end else
My getters and setters look like this for each property:
function get_mdId(){
return $this->mdId;
}
function set_mdId($id){
$this->mdId=$id;
}
And suggestions or ideas?
-TU
Objects are passed around by reference. That means that when you change a value, that value will change everywhere that you have used that object.
As you are storing the same object every time - $this - you end up with an array of references to the same object.
To solve it, you can do:
$mdArray = array();
while($row=mysql_fetch_array($mdSelectALL))
{
$tmp_object = new MyObject; // fill in the name of your object...
$tmp_object->mdId=$row['md_id'];
...
array_push($mdArray, $tmp_object);
}