Вопрос

I am developing a voting system in PHP with MySQL, in which user enter his choice through radio button and this will go in database. On same page, the percentage of user votes appears after clicking submit button.

But the code does not work for more then one time. Please help me to sort out this query.

Further detail

In this program I use database table poll in which I make two columns named yes and no and set their value 0. Then, I use two variables $i and $j for updating the value of yes or no in database on click submit button.

If "yes" is selected then $i increments its value and using an UPDATE query it is saved. I then fetch the value from both yes and no columns to calculate percentage.

I set $_session['yes'] to store the result of percentage of voters who voted "yes", and the same for the variable $_session['no']. Finally, I fetch values from database to store in $i and $j for next click, but the values are not changing.

PHP CODE:

<?php
    ob_start();
    session_start();
    $conn=mysql_connect('localhost','root','');
    mysql_select_db('oop',$conn);
      global $i,$j; 
     if(isset($_POST['btnsav']) && isset($_POST['vote']))
      { if($_POST['vote']=='yes')
     {   $y=$i++;
    $query="update poll set yes='$y'";
    $res=mysql_query($query) or die(mysql_error());
            if($res>0)
            {
                $qry="select yes from poll";
                $res=mysql_query($qry) or die(mysql_error());
                $r=mysql_fetch_array($res) or die(mysql_error());
                $k=$r[0];

                $qry="select no from poll";
                $res=mysql_query($qry) or die(mysql_error());
                $r1=mysql_fetch_array($res) or die(mysql_error());
                $k1=$r1[0];

                $y=$k/($k+$k1);
                $y1=$y*100;
                $_SESSION['yes']=$y1;


            }

         }
               else 

         {
             $n=$j++;       
             $query="update poll set no='$n'";
             $res=mysql_query($query) or die($query);

            if($res>0)
            {

                $qry="select no from poll";
                $res=mysql_query($qry) or die(mysql_error());
                $r=mysql_fetch_array($res) or die(mysql_error());
                $k=$r[0];

                $qry="select yes from poll";
                $res=mysql_query($qry) or die(mysql_error());
                $r1=mysql_fetch_array($res) or die(mysql_error());
                $k1=$r1[0];

                $y=$k/($k+$k1);
                $y1=$y*100;
                $_SESSION['no']=$y1;


         }


          }
       }

                    $qry1="select yes from poll";
                $res1=mysql_query($qry1) or die(mysql_error());
                $r1=mysql_fetch_array($res1) or die(mysql_error());
                $i=$r1[0];

                 $qry2="select no from poll";
                $res2=mysql_query($qry2) or die(mysql_error());
                $r2=mysql_fetch_array($res2) or die(mysql_error());
                $j=$r2[0];
                   echo ceil($i);
                   echo ceil($j);
    ?>

HTML CODE:

<html>
    <head>
        <style>
            .main
            {
                margin-top: 50px;
            }
        </style>
    </head>
    <body>
        <div class="main">
        <center>
            <h2><font color="blue">Vote For India</font></h2>
        <form method="post">
            <tr>
                <td>Ques: Are you support Rahul Gandhi as PM candidate??<br /></td>
            </tr>
            <tr>
                <td>YES<input type="radio" name="vote" value="yes" /><br />
                NO<input type="radio" name="vote" value="no" /><br /></td>
            </tr>
            <tr>
                <input type="submit" name="btnsav" value="VOTE" /><br />
            </tr>
           <?php
                if(isset($_SESSION['yes']))
                {
                    echo ceil($_SESSION['yes']);
                }
                elseif (isset($_SESSION['no'])) 
                {
                   echo 'Non supportrs'.ceil($_SESSION['no']);
                }
                      ?>
        </form>
        </center>
        </div>
    </body>
</html>

PHP CODE:

<?php
ob_end_flush();
session_destroy();
?>
Это было полезно?

Решение

There are a number of misunderstandings in this code, and a few things that are not exactly wrong but could do with improvement.

Firstly, there is no need to declare global $i,$j - outside of a function or method you are already in global context. I am wondering whether you intend these variables to be "for all users" i.e. every time someone clicks "yes", $i is incremented, and every time someone clicks "no", $j is incremented. Unfortunately it doesn't work like that - they will be zero for every run of the script (technically they will start off as uninitialised, and when you increment them they will emit a "variable undefined" notice, and will assume their original value to be zero).

Secondly, you don't need sessions for this program, unless you want to remember something on a per-user user basis, and where that data is not stored in the database. As far as I can tell the only thing you need to store on a per-user basis is their vote, and since that is stored in the database, there is nothing else to remember. (To be fair, you may wish to remember the user has voted, so you can thank them for voting and disable the voting buttons, but that is a weak protection against someone who is intent on voting more than once).

It is not clear what you are using ob_start() and ob_flush() for. I would suggest removing them.

Now, the reason people found your question hard to understand was that the data types of the columns had not been made clear. Normally, voting code stores a row per voter, so one can have some certainty that the votes are not dishonest. That would mean that the yes and no would be Booleans. However, I've worked out that you intend for there to be only one row, and these values are integer counts.

In that case, you need to do an UPDATE using the current value. Here is how to do it for yes:

UPDATE poll SET yes = yes + 1;

As I say, it would be better to redesign this, so each voter's choice is recorded - otherwise someone will vote many times in order to make their preferred candidate appear more popular than is the case.

Lastly, some general tips:

  • Make your indentation accurate. It doesn't matter if you use spaces or tabs, but keep it consistent. Switch on invisible characters in your editor if it helps.
  • Use meaningful variable names. Don't use $qry and $res, use $query and $result. Single letter names are alright for small loops, but not here - use variables that represent what you mean. You will not make a performance saving by having shorter variables.
  • When things don't work as expected, run the code and examine the database. Put in exit() commands in intermediate places and examine your interim results. This is the essence of debugging - work out roughly where your problem is, and narrow it down until you find a source of a bad result.
  • When asking questions about databases, offer the CREATE TABLE SQL in your question, so readers can see the data structure, and show some sample data too. That would have cleared up a lot of initial confusion.
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top