简体   繁体   English

在Twig模板中显示MySQL查询结果

[英]Display MySQL Query Results in Twig Template

I'm implementing my first Twig project. 我正在实施我的第一个Twig项目。 I have a MySQL database. 我有一个MySQL数据库。 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. 没有Twig,查询所有结果并将它们输出到表中非常简单。 However, I'm having some difficulty getting the query to Twig. 但是,将查询发送到Twig时遇到了一些困难。 It seems like a basic task, but I haven't found any similar examples in the Twig documentation or by searching around. 这似乎是一项基本任务,但是我在Twig文档中或四处搜寻都没有找到任何类似的示例。

Twig templates look a lot like Django/Jinja templates, which I'm more familiar with. Twig模板看起来很像Django / Jinja模板,我对此比较熟悉。 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: 此视图的PHP如下所示:

$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. 该脚本应执行一个SQL查询,以数组的形式返回结果集,然后将结果发送到模板。 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: 在您的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). 问题是您要对mysql_fetch_assoc进行1次调用,这将获得第一行(在您的情况下,该行似乎为空)。 Build the array and send it into the template. 构建数组并将其发送到模板中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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