The Final Code - Page 7
January 8, 2001
Conclusion
Just because I hate confusion, here is the code in its entirety.
As a small addition, I added a nice little "Thank you" message
for voting - it helps to let the user know their efforts were
successful. Make sure you do not just cut and paste if you are
trying to learn. Do this yourself and use your imagination
because there are more ways to do this and tons of room for
creativity and enhancement! For a working demo,
visit Enfused.com.
NOTE: Remember to vote at least once before trying to view the
results, else you will get an overlow error!
<%
dim Conn, rs_Questions, rs_Responses
set Conn = Server.CreateObject("ADODB.Connection")
Conn.ConnectionString = "dsn=polldb;database=polldb"
Conn.ConnectionTimeout = 60
Conn.CommandTimeout = 60
Conn.Open
set rs_Questions = Server.CreateObject("ADODB.Recordset")
strSQL = "SELECT TOP 1 * FROM tbl_questions " & _
"ORDER BY PollDate DESC"
rs_Questions.open strSQL, Conn, 3, 3
'TOP 1 returns the topmost record only
recCount = rs_Questions.RecordCount
PollID = rs_Questions("PollID")
PollQuestion = rs_Questions("PollQuestion")
' Extract the options from the database
strSQL = "SELECT * FROM tbl_Responses " & _
"WHERE PollID = " & PollID
set rs_Responses = Server.CreateObject("ADODB.Recordset")
rs_Responses.Open strSQL, Conn, 3, 3
Total = 0
While Not rs_Responses.EOF
Total = Total + rs_Responses("VoteCount")
rs_Responses.MoveNext
Wend
rs_Responses.MoveFirst
While Not rs_Responses.EOF
If Request.QueryString("View") = "true" then
pVotes = (rs_Responses("VoteCount") / Total) * 100
PollOptHTML = PollOptHTML & _
"<tr><td>" & rs_Responses("PollOption") & _
"</td><td>" & pVotes & "%</td></tr>"
rs_Responses.MoveNext
Else
PollOptHTML = PollOptHTML & _
"<tr><td>" & rs_Responses("PollOption") & _
"</td><td><input type=""radio""" & _
"name=""pollopt"" value=""" & _
rs_Responses("PollOptionID") & """></td></tr>"
rs_Responses.MoveNext
End if
Wend
If Request.QueryString("isSubmitted") = "yes" then
strSQL = "UPDATE tbl_Responses " & _
"SET VoteCount = VoteCount + 1 " & _
"WHERE PollOptionID= " & _
Request.QueryString("pollopt") & ";"
If Int(Request.Cookies("PollCookie")("PollID")) <> _
PollID then
Conn.Execute strSQL
Response.Cookies("PollCookie").Expires = Now() + 365
Response.Cookies("PollCookie").Domain = "mydomain.com"
Response.Cookies("PollCookie")("PollID") = PollID
ErrorMsg = "Thank you for voting!"
End if
End if
%>
<html>
<head></head>
<body>
<% if ErrorMsg <> "" then %>
<%= "<b>" & ErrorMsg & "</b><br>" %>
<% end if %>
<form name="poll" action="poll.asp" method="get">
<table width="250">
<tr><td colpan="2">
<%= PollQuestion %>
</td></tr>
<%= PollOptHTML %>
<tr><td colspan="2">
<input type="submit" value="Submit Vote">
<br>
<a href="poll.asp?View=true">View Results</a>
</td></tr>
</table>
<input type="hidden" name="isSubmitted" value="yes">
</form>
</body>
</html>
Tallying the Results - Page 6
Poll Your Visitors with ASP
|