本文出自:迎風閣


 

首先先看底下的完整程式碼

#!/usr/bin/env python
#coding:utf-8

import cgi,sys
import cgitb; cgitb.enable()
import top,middle,bottom
import MySQLdb

def set_form():
    print "<form name='test' action='formtest.py' method='post'>"
    print "姓名:<input type='text' name='user'><br>"
    print "住址:<input type='text' name='adr'><br>"
    print "電話:<input type='text' name='tel'><br>"
    print "行動:<input type='text' name='tel2'><br>"
    print "<input type='submit' name='ok_btn' value='確認存檔'></form>"

def show_data(form):
    #global form
   
    db=MySQLdb.connect(host="localhost",user="帳號",passwd="密碼",db="資料庫名")

    c=db.cursor()
    #c.execute("SET character_set_results = utf8");
    c.execute("SET names utf8")
    sql="insert into user values (null,'%s','%s','%s','%s')" % (form["user"].value,form["adr"].value,form["tel"].value,form["tel2"].value)
    print sql,"<br><br>"
    c.execute(sql)
    c.execute("select * from user order by id")

    row=c.fetchall()

    for i in row:
        for j in i:
            print j,","
        print "<br>"
    c.close()
    db.close()

print "Content-Type: text/html"     # HTML is following
print                               # blank line, end of headers

print "<html>"
print "<head>"
print "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />"
print "<title>CGI script output</title>"
print "</head>"
print "<body>"

form=cgi.FieldStorage()
if not form.has_key("user"):
    set_form()
else:
    show_data(form)

print "</body>"

其實,這段程式的重點是如何取得前端使用者利用FORM傳送過來的資料
form=cgi.FieldStorage()
首先建立一個form資料物件,它會自動將前端使用者所傳送過來的資料,自動放入form物件裡,並且利用『字典變數』的方式來取得資料,利用form["user"]就是取得前端使用者user欄位的資料。
整個程式相當容易解讀,首先建立form物件,並且檢查是否有user這個欄位,如果沒有,那就產生一個使用者可以輸入畫面的FORM,傳回到前端,如果有user這個欄位,就把前端使用者的資料取出來,產生一個新增資料的SQL敘述,把資料存入資料庫中。

arrow
arrow
    全站熱搜

    正義的胖虎 發表在 痞客邦 留言(0) 人氣()