Edison Augusthy
Edison Augusthy

Reputation: 1573

Displaying data on new page in Python

I want to display each row from a database in a <td> in the following index.html page:

$def with(items)
<h1></h1>
<br/>
<br>
<table border="1">
    <tr>
        <th>Name</th>
        <th>address</th>
        <th>number</th>
    </tr>

    <tr>
        <td>//want name here</td>
        <td>//address here</td>
        <td>//number here</td>
    </tr>
</table>

app.py code:

import web
import MySQLdb

urls = (
  '/', 'Index'
)

app = web.application(urls, globals())

render = web.template.render('templates/')

class Index(object):
    def GET(self):
        return render.hello_form()

    def POST(self):
            form = web.input(name="a", newname="s", number="d")
            conn = MySQLdb.connect(host= "localhost", user="root", passwd="", db="testdb")
            x = conn.cursor()
            x.execute("SELECT * FROM details  WHERE name = '%s'" % (form.name))
            conn.commit()
            items = x.fetchall()
            for row in items: 
                conn.rollback()
                conn.close()
                return render.index(items)
    if __name__ == "__main__":
        app.run()

Upvotes: 0

Views: 464

Answers (1)

Himani Agrawal
Himani Agrawal

Reputation: 1272

items (results fetched) will be an array of tuples. Return the array as it is as you want to display whole data on the html and HTML is only rendered once.

app.py code

import web
import MySQLdb

urls = (
  '/', 'Index'
)

app = web.application(urls, globals())

render = web.template.render('templates/')

class Index(object):
    def GET(self):
        return render.hello_form()

def POST(self):
        form = web.input(name="a", newname="s", number="d")
        conn = MySQLdb.connect(host= "localhost", user="root", passwd="", db="testdb")
        x = conn.cursor()
        x.execute("SELECT * FROM details  WHERE name = '%s'" % (form.name))
        items = x.fetchall()       
        conn.close()
        return render.index(items) // return the array of results as a whole
if __name__ == "__main__":
    app.run()

On index.html

$def with(items)
<h1></h1>
<br/>
<br>
<table border="1">
    <tr>
        <th>Name</th>
        <th>address</th>
        <th>number</th>
    </tr>
   $for row in items: 
        <tr>
        <td>$row[0]</td>
        <td>$row[1]</td>
        <td>$row[2]</td>
        </tr>
</table>

Iterate over the items and display them

Upvotes: 1

Related Questions