2012-12-12 20 views
0

我現在有兩個.cgi腳本。我試圖讓用戶在一個網站上輸入一個關鍵字(第一個cgi腳本),然後它會將這些數據發送到下一個cgi腳本。它目前將它發送到下一頁,但我還想將用戶輸入的信息保存到名爲「keywords」的MySQL表中。我很難找出如何做到這一點。這是我的第一個提示用戶輸入關鍵字的cgi腳本:使用Python CGI和MySQL將用戶從表單保存到MySQL表中

#!/usr/bin/env python 
import cgi 
import cgitb 
cgitb.enable() 

form = cgi.FieldStorage() 
keyword = form.getvalue('keyword') 

print 'Content-type: text/html\r\n\r' 
print '<html>' 
print '<h1>Please enter a keyword of your choice</h1>' 
print '<form action="results.cgi" method="post">' 
print 'Keyword: <input type="text" name="keyword"> <br />' 
print '<input type="submit" value="Submit" />' 
print '</form>' 
print '</html>' 

這是我的第二個.cgi文件。在此我想打印從以前的頁面(即正常工作)鍵入,並把它的關鍵字並保存我的MySQL表(這就是問題的所在):

cgitb.enable() 

form = cgi.FieldStorage() 

keyword = form.getvalue('keyword') 

print 'Content-type: text/html\r\n\r' 
print '<html>' 
print keyword 
print '</html>' 

db = MySQLdb.connect(host="", user="", passwd="", db="") 
cursor = db.cursor() 
sql = """INSERT INTO keywords(keywords) VALUES (keywords)""" 
cursor.execute(sql) 
cursor.fetchall() 
db.close() 

基本上我一般來說,MySQL是新的,我很確定這歸結於我的MySQL代碼全部搞砸了,做了我想做的事情。它不會獲取任何錯誤,只是不會向表中添加任何內容。

回答

1

您沒有將任何參數傳遞給cursor.execute方法。

你需要:

sql = "INSERT INTO keywords (keywords) VALUES (%s)" 
cursor.execute(sql, keyword) 

這應該工作,假設你的表稱爲keywords,幷包含一個名爲keywords列。

您可以通過have a look at the MySQLdb user guide瞭解更多信息。


請意識到這簡單的應用程序暴露在最安全的漏洞web應用程序可能會受到(除了SQL注入),其中特別包括XSS attacks

+0

謝謝,正是我要找的 – Neemaximo

相關問題