使用Python CGI和MySQL将用户输入从表单保存到MySQL表中

时间:2012-12-12 03:09:09

标签: python mysql cgi

我现在有两个.cgi脚本。我试图让用户在一个网站上输入一个关键字(第一个cgi脚本),然后它会将该数据发送到下一个cgi脚本。它目前很好地将它发送到下一页但我还想将用户键入的信息保存到名为“keywords”的MySQL表中。我无法弄清楚究竟如何做到这一点。这是我的第一个cgi脚本,它提示用户输入关键字:

#!/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 个答案:

答案 0 :(得分: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