Is there any way to assign values from MYSQL query in flask to an HTML document?

Viewed 27

I am working on a webpage where I do a query in the Python flask app. Following is the query I ran:

cur.execute("SELECT sum(quantity) FROM pydb.products GROUP BY category")

Which Results in: This is the output from the query

I want to access these data one by one to assign them to the following Quantity Part of the HTML code:

<ul id="autoWidth" class="cs-hidden">
          <li class="item-a">
              <div class="box">
                  <div class="slide-img">
                    <img src="static/images/1.webp" alt="1" />
                    <div class="overlay">
                      <a href="/details/camera" class="details-btn">View Details</a>
                    </div>
                  </div>
            
                  <div class="detail-box">
                    <div class="type">
                      <a href="#">Camera & Camcorders</a>
                      <span> </span>
                    </div>
                    <a href="#" class="quantity">  </a>
                  </div>
                </div>
          </li>
          <li class="item-b">
              <div class="box">
                  <div class="slide-img">
                    <img src="static/images/2.jfif" alt="2" />
                    <div class="overlay">
                      <a href="/details/laptop" class="details-btn">View Details</a>
                    </div>
                  </div>
            
                  <div class="detail-box">
                    <div class="type">
                      <a href="#">Laptops</a>
                      <span>  </span>
                    </div>
            
                    <a href="#" class="quantity"> </a>
                  </div>
                </div>
          </li>
          </ul>

1 Answers

As you may see in many tutorials:

Get data from database

all_rows = cur.fetch()

Send data to template

render_tempalte("file.html", data=all_rows)

And inside HTML you may use for-loops to display it (I skip tags).

{% for row in data %}
   {% for item in row %}
      {{ item }}
   {% endfor %}
{% endfor %}

But you may also access item usings indexes [row][column]

{{ data[0][0] }}

{{ data[1][0] }}

Or you may modify data before sending to template

render_tempalte("file.html", laptops=all_rows[0][0], others=all_rows[1][0])

and later

{{ laptops }}

{{ others }}
Related