BaHar AyØub
BaHar AyØub

Reputation: 337

getResult() method Doctrine

What is the format of the array returned using the getResult() method in the following example, using Doctrine and Symfony2:

$query = $this->_em->createQuery('SELECT p.id, p.nameProduct FROM ArkiglassProductBundle:Product p');
        return $query->getResult();

And I would like to know how to access each case and print every row.

Upvotes: 3

Views: 25645

Answers (3)

Manuszep
Manuszep

Reputation: 823

The query returns an array of Users:

array(
    0 => array(username => 'aaa', name => 'bbb'),
    1 => array(username => 'ccc', name => 'ddd')
)

So the $users[0] element means the first user in the list.

You can use a for loop to iterate:

{% for user in users %}
    {{ user.username }} - {{ user.name }}
{% endfor %}

Upvotes: 2

Bevelopper
Bevelopper

Reputation: 75

Are you asking about "0" in $users[0]? I hope I am not misunderstanding your question. getResults() returns an array of database results. Once you've given your array a name you can access each element using the index. Of course if you want to loop over it you will probably use a foreach loop so you won't have to use the index:

$products = $query->getResults();
foreach ($products as $product){
    echo $product->id.' '.$product->nameProduct;
}

This said... this pseudo code is here for the sake of explanation. If you are using Symfony you will have to display your results in a view file, probably using twig like Manuszep did in his example. In his case you will have to use a for in loop like he did.

Upvotes: 2

snyx
snyx

Reputation: 1104

<?php
$query = $em->createQuery('SELECT u.username, u.name FROM CmsUser u');
$users = $query->getResults(); // array of CmsUser username and name values
echo $users[0]['username'];

taken from the doctrine documentation

Upvotes: 4

Related Questions