2016-09-30 22 views
0

我想在<td>在下面的index.html頁面顯示從數據庫中的每一行:顯示新的頁面上的數據在Python

$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代碼:

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() 
+0

是,一個SQL注入我看到這裏? – Aif

+0

我沒有得到你..?@ aif – Edison

+0

如果名字=''union select'concat(login,':',password)from user where'admin'會發生什麼? (是的,這是僞代碼)請參閱https://www.owasp.org/index.php/SQL_Injection – Aif

回答

1

項目(獲取的結果)將是一個元組數組。按照原樣返回數組,因爲您希望在HTML上顯示整個數據,並且HTML只會呈現一次。

app.py代碼

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() 

在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 
+0

其不顯示任何東西,只是顯示空白頁 – Edison

+0

嘗試檢查數據是否被提取。嘗試打印在app.py中獲取的項目並渲染一個不同的模板,它將打印所有項目。要渲染新的模板,請執行:$ def with(items) $ items' –

+0

我認爲數據沒有被提取,所以我應該怎麼做全新的python – Edison

相關問題