Home > Back-end >  Trying to display all records in HTML but it is only presenting last item from the database in the H
Trying to display all records in HTML but it is only presenting last item from the database in the H

Time:09-17

This code only outputs the final record in the Sqlite table. It does not output ALL records from the table into the HTML. Any suggestions?

import sqlite3    
from flask import Flask, render_template, redirect, request   
app = Flask(__name__)

connection = sqlite3.connect('employee.db')

cur = connection.cursor()
cur.execute('SELECT * FROM employee;')
s = "<table style='border:2px solid black'>"
for row in cur:    
    s = s   "<tr>"    
for x in row:    
    s = s   "<td>"   str(x)   "</td>"    
    s = s   "</tr>"    
cur.close()

@app.route('/')  
def main():    

    return "<html><body>"   s   "</body></html>" 

if __name__ == "__main__": 
    app.run()

CodePudding user response:

Nest the second for x in row loop in the for row in cur loop to make sure it is run for every row

This should solve your problem.

import sqlite3    
from flask import Flask, render_template, redirect, request   
app = Flask(__name__)

connection = sqlite3.connect('employee.db')

cur = connection.cursor()
cur.execute('SELECT * FROM employee;')
s = "<table style='border:2px solid black'>"
for row in cur:    
    s  = "<tr>"    
    for x in row:    
        s  = "<td>"   str(x)   "</td>"    
        s  = "</tr>"    
cur.close()


@app.route('/')  
def main():    
    return "<html><body>"   s   "</body></html>" 


if __name__ == "__main__": 
    app.run()
  • Related