This week, I will teach you how to write a class for poll. Basically, you need to write static function to:
- query your poll question id, question, answer, option count, total vote count and status from tbl_poll
- query user voted record to check whether user has voted before or not.
- Do delete record from tbl_user_vote and insert user_id, qst_id and option value if he has voted.
- Update option count and total vote count.

You can create php file named Poll.php
class Poll {
public static function GetPollQuestion() {
$sql = InfoDb::query(
‘SELECT qst_id, qst, ans1, ans2, ans3, ans4, opt1, opt2, opt3, opt4, votes, status FROM ‘ //the field name is case insensitive, e.g, you can put Qst_id, Qst….
.tbl_poll’ //make sure this table name is same with your table name set in database
.’ WHERE status=1′,
NULL,
NULL
);
$row = $sql->fetchRow();
return self::GetPollQuestionRowObject($row);
}
public static function GetUserVote ($qst_id,$userid) {
$sql = InfoDb::query(
‘SELECT user_id, qst_id, `option` FROM ‘ //you must use correct escape character for the word option, use this “ in stead of ‘’
.’tbl_user_vote’
.’ WHERE qst_id=? and user_id=?’, //set to ? is to prevent sql injection
array(‘integer’,‘integer‘),
array($qst_id, $userid)
);
$row = $sql->fetchRow();
return self::GetUserVoteRowObject($row);
}
public static function UserVoteOption( $userid, $qst_id, $option) {
InfoDb::dml(
“DELETE FROM tbl_user_vote”
.” WHERE qst_id=? and user_id=?”,
array(‘integer’,‘integer’),
array($qst_id,$userid)
);
return InfoDb::dml(
“INSERT INTO tbl_user_vote”
.” (user_id, qst_id, `option`)”
.” VALUES (?,?,?)”,
array(‘integer’,‘integer’,‘integer’),
array($userid, $qst_id, $option)
);
}
public static function IncreasePollAnswerCount($qst_id, $option) {
return InfoDb::dml(
“UPDATE tbl_poll”
.” SET opt$option=opt$option+1, votes=votes+1″
.” WHERE qst_id=?”,
array(‘integer’),
array($qst_id )
);
}
}
What Is SQL Injection?
