简体   繁体   中英

Display MySQL Query Results in Twig Template

I'm implementing my first Twig project. I have a MySQL database. It includes a table where each record is a document. There are Title, Number, and Description fields.

Without Twig, it was pretty straightforward to query all the results and output them to a table. However, I'm having some difficulty getting the query to Twig. It seems like a basic task, but I haven't found any similar examples in the Twig documentation or by searching around.

Twig templates look a lot like Django/Jinja templates, which I'm more familiar with. My template:

{% block Content %}

<table border='1' width=100%>
    {% for i in queryResult %}
    <tr>
        <td> {{i.Title}} </td>
    </tr>
    {% endfor %}
</table>
{% endblock %}

The PHP for this view looks like this:

$connection=mysql_connect (credentials) or die ('Cannot connect to database:' . mysql_error());
    $mydb=mysql_select_db(database);

$sql = query;

$query = mysql_query($sql);

$result = mysql_fetch_assoc($query);

echo $twig -> render('all_reports.html', array('queryResult'=> $result));

Which seems right. The script should execute a SQL query, return the resultset as an array, and then send the result to the template. The template should iterate over all the items in the array (one item for each row) and display them in a table.

What actually happens is that a three rows are rendered, all blank. My interpretation is that the template sees three items in the array (one for each field) instead of an item for each record in the query result. They are blank because each field doesn't have a Title field. But I'm at a loss as to what would fix this.

Try this in your PHP:

while ($row = mysql_fetch_assoc($query)) {
    $results[] = $row;
}
echo $twig -> render('all_reports.html', array('queryResult'=> $results));

The problem is that you are making 1 call to mysql_fetch_assoc which will get the first row (which seems to be blank in your case). Build the array and send it into the template.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM