Last Updated:

Voting on the PHP!

Voting on the PHP

We will talk about the practical work that we will carry out and assimilate together. Voting is a means of finding out the opinion of your visitors on various issues. The questions themselves can be both useful and useless - we will not consider this topic. And for our example, let's take a simple question - what is your opinion about the site?

For example, suppose you have a desire to know what most visitors to your website think. We will provide the following answer options:

  1. Steeply!
  2. That's all right.
  3. I don't care.
  4. It's something scary.

You can continue the list yourself... To work, we'll need some knowledge of the basics of HTML, PHP version 3 or higher, and three files. Three - because in the first we will ask the visitor about his opinion, in the second we will store the results, and in the third - to display them and process them. Strictly speaking, there is no need to distribute all these functions into different files, but for simplicity and convenience, we will do so.

The first file will be named index.phtml, the second - golos.txt and the third - golos.phtml. Creating them for you will not be difficult, and this is where we will start. When you've done everything and uploaded the finished files to your server, don't forget to set the attributes of the golos file.txt in such a way that it is writable. Usually, these are attributes 666 or 777.

This can usually be done using your FTP manager. If not, use IE 5.0 and higher in FTP mode, then you just need to see the properties of the file already uploaded to the server and check all the boxes.

Index.phtml

You can call this and our other files however you like, just do not change the extensions (except, of course, txt). This is necessary for the work of the PHP, on which the voting algorithm will be implemented. I suggest you do the design and decoration yourself, I will not pay attention to this in the article. First of all, we will make the desired form. You could use any HTML editor, they do a good job of making the forms themselves, but I'm already providing ready-made and workable code.

<FORM METHOD="POST" action="golos.phtml">
<TABLE BORDER=1><TR><TD><TABLE BORDER=0>
<TR><TD>What is your opinion about the site?</TD></TR>

<TR><TD><INPUT TYPE=radio NAME=answer VALUE=1>Cool!</TD></TR>
<TR><TD><INPUT TYPE=radio NAME=answer VALUE=2>Normal</TD></TR>
<TR><TD><INPUT TYPE=radio NAME=answer VALUE=3>I don't care</TD></TR>
<TR><TD><INPUT TYPE=radio NAME=answer VALUE=4>This is something scary!</TD></TR>

<TR><TD><INPUT TYPE=Submit NAME=vote VALUE=" submit "></TD></TR>
<TR><TD><INPUT TYPE=Submit NAME=result VALUE=" view result
"></TD></TR></TABLE></TD></TR></TABLE></FORM>

That's all for now. There's not a line of PHP code here, but it's useful for the future to be able to insert something here, so the file extension is chosen correctly, especially since it doesn't affect anything else. In the code, everything is simple, and it is easy to do this or similar in any editor. We simply offer to specify the desired answer option using the switch and click on the Send button.

This code can be easily integrated into any pages and edited as soon as you like. Just pay attention to the correspondence of the names and values of the variable in the form. And most importantly - the form data must be passed to the PHP script with the processing of the results, so the file name in action must correspond to the name of the file with the script.

As a reminder, all form names assigned in this file will become corresponding variables in the PHP script to which the form data is sent. Since nothing complicated is expected here, let's move on.

Golos.txt

Here we need to decide in what format we will store the entered information. The easiest way is to organize four lines (by the number of answer choices) and consider their numbers to correspond to the number of the selected answer option. All this ugliness can be read using the PHP command to enter a file into the array, but do not forget that the array always begins with index zero.

Accordingly - the first line of our file will not be used, and you can enter anything there. For example - information about the file: Voting results. If you do, enter four more lines with zeros. Don't forget to press the input to translate the line.

These are the finished results (so far only the initial ones) of our vote. Since no one has voted yet :-) they're zero.

Golos.phtml

So we have reached the most important and interesting. From the very beginning, I will give all the code of the script, and then I will give explanations in its application and operation.

<?php
$file = "golos.txt";
$a = file($file);
$i = 1; $fi = Count($a);
$n = 0;
while ($i <= $fi):
$a[$i] = trim(str_replace("\n","", $a[$i]));
$n = $n+$a[$i];
$i++;
endwhile;

if ($answer != "") {
echo "<br>Thank you, your opinion is appreciated:";
$a[$answer]++; $n++;

$rez = "Voting results!\n".$a[1].
"\n".$a[2]."\n".$a[3]."\n".$a[4];
$fp = @fopen($file,"w");
if ($fp) { $counter=fputs($fp,$rez); fclose($fp); }
else { echo "There was an error writing results!"; }

} else { echo "<br>Voting results"; }
echo "<br>Cool! - <b>".$a[1]."</b>";
echo "<br>So-so - <b>".$a[2]."</b>";
echo "<br>Fine - <b>".$a[3]."</b>";
echo "<br>This is something scary! - <b>".$a[4]."</b>";
echo "<br><br>Total votes: ".$n;
?>

Again, I want to warn you that the code is not the best and simplest, but it is logical and workable. There are a lot of options for implementation, but I did not want to take something ready-made, and therefore I, not really caring about readability and design (you can do it yourself :-), wrote my own code, which took literally half an hour along with configuration and debugging.

The script is focused on a specific task, but it costs you nothing to redo it for your number of answers to the question. Let me remind you that our main task is to learn how to create our own polling and voting systems using a practical example.

In the first lines, we define the name of the results file and read the voting results into a data array named $a. Then there is a loop in which we process the resulting array in such a way that it does not contain carriage translation characters (line input) and spaces:

$a[$i] = trim(str_replace ("\n","", $a[$i]));

In parallel, we count the number of voters, which is not difficult since it is simply the sum of the values of our array. Removing the input and space characters is necessary to convert the read data from a character string to an integer. This can be done by different methods, but in this case, the characters are simply removed (which in PHP corresponds to the line feed) and the spaces are cut off from the beginning and from the end of the line by the function ."\n"trim ( )

The results are written back to the array, but already in the form of an integer value that can be added, enlarged, divided, etc.

We will be interested in increasing by a unit a certain element of the array, the number of which (its index) is stored in the variable , which in turn came to us by inheritance from the form.$answer

After processing the resulting array, the script must make a decision regarding the mode chosen by the visitor - either simply show the results, or add a voice to the appropriate position. This is achieved by checking the variable , which stores the value of the voting option chosen by the site visitor.$answer

If this variable is empty, then the show results button has been clicked, and the script will skip the vote counting block. If the variable $answer is not empty, it contains the number of the selected voting option, which means that we can simply increase the value of the desired array cell by one:

$a[$answer]++;

In addition, it is necessary to increase the value of the number of voters in order to take into account the vote of the person who has just voted.

When the desired array cell is enlarged, it is time to write the results to a file. To do this, you first open a connection to the file:

$fp = fopen($file,"w");

The symbol indicates that the contents of the file must be cleared before writing. If the connection is not established, an error message is displayed if it is established - the pre-formatted value of the variable is written to the file. The variable is formed as follows: the value of all cells of the array (except for the very first one - zero, which is not used) is glued in such a way that the separator is the line feed character.w$rez$rez

This will allow in the future to correctly read the file received in this way. To glue lines in the PHP, a dot separator is used. Note that our array has moved from integer to character array, and can be used and processed in any available PHP way.

And finally - it's time to bring the results to the screen. Do not forget about the line feed in HTML, which is somewhat different than in PHP. This is done by simply displaying on the screen (and therefore in the HTML code) the tag . When the formatted results are displayed, the script finishes its work. This block can also be organized in different ways, and the method used here is the simplest.<BR>

It is best to put the results and points in the table, then the displayed information will look more beautiful. If you noticed, this part of the script is executed in any case, as well as reading data from the file. Thus, a guaranteed display of the results on the screen is achieved.

That's all the work. I hope that you will now be able to easily organize surveys of your visitors on various topics. In addition, voting can be equipped with other useful functions – for example, counting the percentage of votes, a graphical representation of the results, memory on the IP of the respondent, so that they do not vote twice. Yeah, not much...