Creating a Voting Poll With PHP And MySQL Part 1/2
Voting polls provide a level of interactivity in a sense that visitors can express their opinions about particular topics and areas of interest, simply by choosing their response to a question and clicking on a vote button. In this series of two articles, Mitchell's going to show us how to create an interactive voting poll system. It will contain an admin page and a page to vote and view results.
Creating a Voting Poll With PHP And MySQL Part 1/2 - Deleting a poll from the database (Page 4 of 5 )
The GetChoice function also allows us to delete a poll by hyper linking us to managepoll.php?method=ShowDelete, which in turns calls the GetPollToDelete function.
The GetPollToDelete function display a HTML form with a drop-down list containing each poll in the pollQuestions database. The code for the drop-down list looks like this:
Each option in the drop-down list displays the polls questions. Its value, however, contains the pk_Id value of the poll. I have chosen to use the mysql_fetch_row function to retrieve each poll from the database, however you could also use the mysql_fetch_array function to reference the fields by name instead of number.
As you can probably guess, the HTML form created by the GetPollToDelete function also tacks a "method" variable onto the end of the <form> tags action attribute, like this:
The HTML form generated by the GetPollToDelete function looks like this:
Once we click on the "Delete Selected Poll" button, our PHP script picks up the value of the "method" variable as "DeleteFinal" and calls the DeletePoll method, which actually removes the poll and any votes that visitors may have posted to the pollAnswers table (We will look at voting in the next article).
The drop-down list that we used to select the poll to delete is called "pollId", and PHP automatically gives us access to its value by creating a variable named $pollId. We need to use a global reference to get access to it:
global $pollId;
The drop down list's first option is "-- Select Poll --" and contains the value zero. If $pollId is zero, then the user didn't select a poll to delete. We use a simple if...else statement to check this:
If($pollId > 0)
{
// Poll selected
}
else
{
// No poll selected
}
If the user has selected a poll, we execute two delete queries against our MySQL database: One to remove the poll from the pollQuestions table, and the other to remove any votes from the pollAnswers table that the poll may have attained while it existed in the database:
$strQuery1 = "DELETE FROM pollQuestions WHERE pk_Id = $pollId";
$strQuery2 = "DELETE FROM pollAnswers WHERE pollId = $pollId";
if(!mysql_query($strQuery1))
die("Couldn't delete from pollQuestions table");
if(!mysql_query($strQuery2))
die("Couldn't delete from pollAnswers table");
?>
<h1>Poll Deleted Successfully</h1>
You have successfully delete poll number <?php echo $pollId;?> from the polls database.