Franj
Franj

Reputation: 137

Silex and Doctrine mysql: how to return results from select all

The Doctrine provider provides a db service. Here is a usage example:

$app->get('/enc/{id}', function ($id) use ($app) {
    $sql = "SELECT * FROM encuestas WHERE id_enc = ?";
    $post = $app['db']->fetchAssoc($sql, array((int) $id));

    return  "<h1>Encuestas</h1>".
                "<p>{$post['fec_enc']}</p>".
                "<p>{$post['opc1']}</p>".
                "<p>{$post['img1']}</p>".
                "<p>{$post['vot1']}</p>".
                "<p>{$post['opc2']}</p>".   
            "<p>{$post['img2']}</p>".
            "<p>{$post['vot2']}</p>".
            "<p>{$post['estado']}</p>";
});

this is array, the problem:

$app->get('/enc', function() use ($app) {


    $sql = "SELECT * FROM encuestas";
    $post = $app['db']->fetchAll($sql);


   return   ...;

});

Upvotes: 1

Views: 3360

Answers (1)

Alex
Alex

Reputation: 1183

And what is a problem?

In the second piece of code db returns the array of associated arrays. and to show each item from it you have to use some kind of loop. The return example you provided is ugly, actually. Why don't you use some template engine (like twig for example)? Anyway you have to do something like:

$posts = $app['db']->fetchAll($sql); // posts - NOT post
foreach($posts as $post) {
    echo $post['fec_enc']; // or "echo '<p>' . $post['fec_enc'] . '</p>'", 
                           // but it's really ugly
    ... // rest of properties
}

Or using twig:

Render twig template:

return $app['twig']->render('<template_name>', array('posts' => $posts));

In twig template:

{% for post in posts %}
    {{ post.fec_enc }}
    ...
{% endfor %}

Here is more about Silex templates: http://silex.sensiolabs.org/doc/providers/twig.html

Upvotes: 4

Related Questions