PHP Survey code

 

This lesson is part of an ongoing Survey/Poll tutorial. The first part is here: Build your own Survey/Poll, along with all the files you need.

In the previous part lesson, you had a look at the PHP code to set a question for your survey. We'll now look at the code for the actual survey.In a web browser, it looks like this:

The HTML form for this consists of three RADIO tags and two SUBMIT tags. (The SUBMIT tag gets you a button.) Here's the HTML for the form:

<FORM NAME ="form1" METHOD ="GET" ACTION ="process.php">

<P><?PHP print $question; ?>
<P><INPUT TYPE = 'Radio' Name ='q' value= 'A' <?PHP print $answerA; ?>><?PHP print $A; ?>
<P><INPUT TYPE = 'Radio' Name ='q' value= 'B' <?PHP print $answerB; ?>><?PHP print $B; ?>
<P><INPUT TYPE = 'Radio' Name ='q' value= 'C' <?PHP print $answerC; ?>><?PHP print $C; ?>

<P><INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Click here to vote">
<INPUT TYPE = "Hidden" Name = "h1" VALUE = <?PHP print $qID; ?>>

</FORM>

<FORM NAME ="form2" METHOD ="GET" ACTION ="viewResults.php">

<INPUT TYPE = "Submit" Name = "Submit2" VALUE = "View results">
<INPUT TYPE = "Hidden" Name = "h1" VALUE = <?PHP print $qID; ?>>

</FORM>

The thing to note here is that there are two forms between the BODY tags. The first, with the NAME form1, is for the "Click here to Vote" button. The ACTION for this form is process.php. This is a separate file that we'll look at soon. The second form, with the NAME form2, is for the "View Results" button. The ACTION for form2 is viewResults.php. Again, this is a separate page that we'll look at later.

There are one or two things to note about form1. First, there's a print statement at the top:

<?PHP print $question; ?>

This will print out the question. The second thing to note is the HTML RADIO buttons:

<INPUT TYPE = 'Radio' Name ='q' value= 'A' <?PHP print $answerA; ?>><?PHP print $A; ?>
<INPUT TYPE = 'Radio' Name ='q' value= 'B' <?PHP print $answerB; ?>><?PHP print $B; ?>
<INPUT TYPE = 'Radio' Name ='q' value= 'C' <?PHP print $answerC; ?>><?PHP print $C; ?>

All three RADIO buttons have the same NAME: 'q'. This is so that they are treated as one group. The VALUE is either A, B, or C. We'll get the value with PHP code. The first print statements ($answerA, $answer and $answerC) are for the CHECKED property of RADIO buttons. We need to know which button the user selected (checked). The second print statements ($A, $B, $C) are for the three choices that we'll pull from the database table.

The HTML for form2 is just a HIDDEN tag. It has the NAME h1 and prints an ID. We'll grab these when the form is sent to the viewResults.php page.

Let's have a look at the PHP code for survey.php. It's this:

PHP code for survey (opens in a new browser tab as a text file)

The first part of the code is for getting a value from the setSurvey page. If you remember, this page has a dropdown list where you can set a question for your survey. It passes over the ID number from the database table. This is what we're getting:

if (isset($_GET['h1'])) {

$qID = $_GET['h1'];

} else {

$qID = 1;

}

The isset part will only activate if it can GET a value with called h1. This h1 value is passed over from setSurvey.php. If all is OK, then we place the ID from setSurvey into a variable called $qID. This will contain an ID from the database table. If it can't get a value for h1 then we're setting a default value for $qID - 1. This means row 1 from the table. There would be a problem here, if you didn't have a row with an ID of 1. So you could query the database and grab any valid ID to use as a default. We're assuming there is a row 1, which is not the wisest thing to do! But we don't want to overcomplicate things.

The next few lines set up some variables:

$question = 'Question not set';

$answerA = 'unchecked';
$answerB = 'unchecked';
$answerC = 'unchecked';

$A = "";
$B = "";
$C = "";

If a question can't be set, we're storing some defaults for the question, and the three choices, A, B and C. We're also leaving the RADIO buttons unchecked.

After attempting to contact the server and database, we have our prepared statement:

$stmt = $db_found->prepare("SELECT ID, Question, OptionA, OptionB, OptionC FROM tblsurvey WHERE ID = ?");

Again, we're only selecting the columns we need in the SQL:

SELECT ID, Question, OptionA, OptionB, OptionC FROM tblsurvey WHERE ID = ?

The only columns we need are ID, Question, OptionA, OptionB and OptionC. But we need to match an ID, which is why we have the question mark after the WHERE clause.

If the statement is OK, we can bind the parameters:

$stmt->bind_param('i', $qID);

The letter 'I' means Integer, because that's what we set up our ID field as. The ID itself will be held in the variable called $qID.

Next, we execute the statement and try to get some rows back:

$stmt->execute();

$res = $stmt->get_result();

If we find some rows, we can fill up our variables:

if ($res->num_rows > 0) {

$qID = $row['ID'];

$question = $row['Question'];

$A = $row['OptionA'];
$B = $row['OptionB'];
$C = $row['OptionC'];

}

So we access the Question, OptionA, OptionB and OptionC fields from the database and place the values into the variables called $question, $A, $B, $C.

And that's all we need to do. The rest of the PHP code is just some error checking, with lots of else parts to the if statements.

When the user selects an option, and activates the "Click here to vote" button, then they will be sent to the process.php page. That $qID variable above will be sent to the process page. Also sent to the process page is the choice the user made (A, B or C).

Let's have a look at the process page.

 

The process.php Page

The process page is used for processing the choice that a user made in the survey. That choice is added to the survey database table, and a suitable message is displayed once the vote has been added. To do all that, it needs two things from the survey.php page: the choice that the user made (A, B or C), and a question row ID from the table.

The row ID is contained in the $qID variable from the survey page. We placed this in a HIDDEN HTML tag:

<INPUT TYPE = "Hidden" Name = "h1" VALUE = <?PHP print $qID; ?>>

On the process page, we can use GET to grab that ID, simply by using the NAME value, which was h1. When a RADIO button is clicked, you can also just GET the NAME value. Each RADIO button was given the NAME 'q':

<INPUT TYPE = 'Radio' Name ='q' value= 'A' <?PHP print $answerA; ?>><?PHP print $A; ?>
<INPUT TYPE = 'Radio' Name ='q' value= 'B' <?PHP print $answerB; ?>><?PHP print $B; ?>
<INPUT TYPE = 'Radio' Name ='q' value= 'C' <?PHP print $answerC; ?>><?PHP print $C; ?>

If you use $_GET['q'] then you can grab the VALUE, which we have as A, B or C, in the code above. Here's the entire code for the process.php page:

PHP code to process the survey (opens in a new browser tab as a text file)

When testing this code, locate the following line:

$_SESSION['hasVoted'] = '1';

Comment this line out, otherwise you'll get the message "You've already voted" whenever you try to add a new vote to your database. You may even need to close your browser down and open it up again, depending how you've got your cookies set up. Don't forget to uncomment the line, if it's going onto your website. But it's there to set a session variable called hasVoted. We can check for this at the top of the code:

session_start();

if ((isset($_SESSION['hasVoted']))) {

if ($_SESSION['hasVoted'] = '1') {

$voteMessage = "You've already voted";

}

}

This checks if a session called hasVoted has been set. We next check if the hasVoted session is set to a value of 1. If both of these things are true then it means that the user has already voted. (Of course, you could just clear out your cookies and vote again. But this is not exactly an app that guards the Crown Jewels! A more robust app might create a temporary database table and record that the user has voted there.)

If the user hasn't voted, the else part of the if statement is executed. First up is this piece of code:

if (isset($_GET['Submit1']) && isset($_GET['q'])) {

$selected_radio = $_GET['q'];
$idNumber = $_GET['h1'];

This checks if the Submit button on the previous page was clicked. It also checks if the q variable is set. This q variable, remember, is holding a value from our RADIO buttons. It will be A, B, or C, depending on which option was selected.

If both of these things are true, we can go ahead and store the values into variables:

$selected_radio = $_GET['q'];
$idNumber = $_GET['h1'];

The variable $selected_radio will hold the A, B or C option; the $idNumber variable will hold the row ID from our database table.

The next part of the code connects to the server and database, where we create a new mysqli object (you've met this code before):

$db_found = new mysqli(DB_SERVER, DB_USER, DB_PASS, $database );

We then have an if statement that checks if the database object is valid:

if ($db_found) {

}

If the database and server are found, we need to check of the selected RADIO button hold a value of A, B or C:

if($selected_radio == "A") {
}
else if($selected_radio == "B") {
}
else if($selected_radio == "C") {
}
else {

print "Error - could not record vote";

}

If $selected_radio is not A, B or C then we print a message: Error - could not record vote.

The code for these if … elseif … statements, first builds a prepared statement:

$votedSQL = "UPDATE tblsurvey SET VotedA = VotedA + 1 WHERE ID = ?";

We want to UPDATE the table and SET a new value. Notice this part:

VotedA = VotedA + 1

The field in the table called votedA will be incremented by 1, with this code. The WHERE part at the end is for matching the correct row in the table with the ID value we're going to be passing it.

To prepare, bind, and execute the SQL, we have this line:

$voteMessage = insert_vote($db_found, $votedSQL, $idNumber);

This is a call to a function at the bottom of the code. This function:

function insert_vote($db, $sql, $id) {

$stmt = $db->prepare($sql);
$stmt->bind_param('i', $id);
$stmt->execute();

//$_SESSION['hasVoted'] = '1';

return "Thanks for voting!";

}

We're passing the function three things: the database object ($db) the SQL we want to use for prepare, and that ID number. These are used on the first two lines:

$stmt = $db->prepare($sql);
$stmt->bind_param('i', $id);

The parameters for bind are i and $id. The i stands for integer, and the $id variable holds the row ID for the surveytable.

After executing prepared statement, we then set up the session:

$_SESSION['hasVoted'] = '1';

This places a value of 1 in the session called hasVoted. Once we set something in the session variable, it means the user can't vote over and over again, because they'll get that message, "Already voted".

The final thing we do with the function is to return a message:

return "Thanks for voting!";

And that's about it for the process.php page. The whole point of the code is to record a vote in the database, and prevent users from voting repeatedly.

We'll now take a look at the viewResults.php code.