0

I am beginner and trying constantly to print value on web page through cgi-bin but i dont know what i am doing wrong. I gone through different tutorials like:

http://www.inmotionhosting.com/support/website/python/how-to-use-python-to-connect-to-a-database

http://ianhowson.com/a-quick-guide-to-using-mysql-in-python.html

http://www.tutorialspoint.com/python/python_database_access.htm and some threads as well like: Returning Output of Python CGI MySQL Script because i think i am doing wrong somewhere but fail to print.

here is my code and it only prints "hello":

#!C:\Python27\python.exe

import cgi
import cgitb

print "Content-type: text/html\n"
print """
<html>
<head>
<p> hello</p>
</head>
"""

import MySQLdb

db = MySQLdb.connect(host="127.0.0.1",port=3306, user="root", passwd="",db="project")


cursor = db.cursor()
cursor2 = db.cursor()
# execute SQL select statement
#sql = "SELECT stid,firstname FROM student WERE stid IN(SELECT stid FROM stobt WHERE stid=%s" % (0)

sql2 = "SELECT stid FROM student  WHERE firstname = '%s'" % ('User')


# Execute the SQL command

cursor2.execute(sql2)
# Fetch all the rows in a list of lists.

result2 = cursor2.fetchall()
#print result2

row2 = result2[0]
#print 'r1',row[1]
#print 'r2',row2[0]
sql = "SELECT * FROM stobt  WHERE stid = '%d'" % (row2)
cursor.execute(sql)
results = cursor.fetchall()
row = results[1]
tc = 56
for row in results:

   if row2[0] == row[1]:
      idd = row[0]
      stid = row[1]
      obtained = row[2]
      subject = row[3]

   # Now print fetched result

      print( "<h1>id=%s,stid=%s,obtained=%f,subject=%s</h1>" %(idd, stid, obtained, subject ))

print """
<body>
<p> idd</p>
</body>
</html>
"""
    #  if obtained <= 50:
     #    if tc >= 50:
      #      print tc
db.close()      

Any idea?

7
  • It may not be the only problem, but your HTML is completely broken. Your h1 must be inside the body element, which means you need to print <body> before you do the SQL stuff. Note also that your "hello" string should also be inside the body, not the head. Commented Mar 8, 2016 at 17:24
  • i placed <body> after </head> and yet no printing of sql db values..... Commented Mar 8, 2016 at 17:41
  • So, what does the generated source look like (if you do View Source in your browser)? Does it have the right data? Commented Mar 8, 2016 at 18:10
  • <html> <head> </head> <body> <p>hello</p> </body> </html> Commented Mar 8, 2016 at 18:24
  • OK, do you actually have a user with the firstname "User" in your student table? Do you have any records with that user's id in your stobt table? Commented Mar 8, 2016 at 18:27

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.