How to get selected radio button's value inside of a servlet and store it inside DB?

I am developing a voting application where one can vote for a specific option and submit it. Now, I want the user's selected option inside of a servlet and store it as a vote inside the database. And that count should always increment by 1 when received a new vote. But, it's not giving me the desired output. Every time when I select an option and click submit, 1 gets inserted into the respective column of the database like a vote. I have named the options as column names within the db. I want that every new vote is an addition to its previous value

Following is the Voting.jsp page:-

<div class="card" style="width: 60rem; margin-left: 45px;">
  <div class="card-body">
  Click on one of the following options to caste your vote. Then click submit.

  </div>
  </div>


<div class="card" style="width: 60rem; margin-left: 45px;">
  <div class="card-body">
  <form action="SuccessServlet" method="post">
    <label class="container">Team_1
  <input type="radio" name="radio" value="team1">
  <span class="checkmark"></span>
</label>
<label class="container">Team_2
  <input type="radio" name="radio" value="team2">
  <span class="checkmark"></span>
</label>
<label class="container">Team_3
  <input type="radio" name="radio" value="team3">
  <span class="checkmark"></span>
</label>
<label class="container">Team_4
  <input type="radio" name="radio" value="team4">
  <span class="checkmark"></span>
</label>
<button type="submit">Submit</button>
</form>
  </div>
</div>

and the following is my Servlet class:-

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {



        ud.setFirst_name(request.getParameter("f1"));



        String answer = request.getParameter("radio");

        if("team1".equals(answer)) {

            System.out.println("Hello");

            writeData1();

            }

    else if ("team2".equals(answer)) {

        writeData2();

    }

    else if ("team3".equals(answer)) {

        writeData3();
    }

    else if ("team4".equals(answer)) {

        writeData4();
    }

    else {
        response.sendRedirect("Success.jsp");
    }
    response.sendRedirect("UserPage.jsp");

}



    }


      public void writeData1() {

      try {
        Class.forName("com.mysql.cj.jdbc.Driver");


      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_db?autoReconnect=true&useSSL=FALSE", "root", "root");


      String query = "insert into Total_Votes(Team1) values(?)";

      PreparedStatement ps = con.prepareStatement(query);

      ps.setInt(1, 1);

      ps.executeUpdate();


      } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println(e.getMessage());
        }





  }





public void writeData2() {

      try {
        Class.forName("com.mysql.cj.jdbc.Driver");


      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_db?autoReconnect=true&useSSL=FALSE", "root", "root");


      String query = "insert into Total_Votes(Team2) values(?)";

      PreparedStatement ps = con.prepareStatement(query);

      ps.setInt(1, 1);

      ps.executeUpdate();


      } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println(e.getMessage());
        }





  }





public void writeData3() {

      try {
        Class.forName("com.mysql.cj.jdbc.Driver");


      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_db?autoReconnect=true&useSSL=FALSE", "root", "root");


      String query = "insert into Total_Votes(Team3) values(?)";

      PreparedStatement ps = con.prepareStatement(query);

      ps.setInt(1, 1);

      ps.executeUpdate();


      } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println(e.getMessage());
        }





  }




public void writeData4() {

      try {
        Class.forName("com.mysql.cj.jdbc.Driver");


      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_db?autoReconnect=true&useSSL=FALSE", "root", "root");


      String query = "insert into Total_Votes(Team4) values(?)";

      PreparedStatement ps = con.prepareStatement(query);

      ps.setInt(1, 1);

      ps.executeUpdate();


      } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println(e.getMessage());
        }





  }

Upvotes: 0

Views: 501

Answers (2)

Swati
Swati

Reputation: 28522

suppose team1 radio button is selected, now you need to get value of previous votes of team1 using select query like below :

   try {
            Class.forName("com.mysql.cj.jdbc.Driver");
          Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_db?autoReconnect=true&useSSL=FALSE", "root", "root");
    String sql="select votes from Total_Votes where team=?";
                     int votes=0;
                    PreparedStatement ps = con.prepareStatement(sql);
                   ps.setString(1,"team1");//passing team1 in query
                   rs = ps.executeQuery();
                    while(rs.next())
                   {
          votes=rs.getInt("yourcoulmnname");//getting value of coulmn where votes are stored for team1
                  }
                   }catch(Exception e)
                   {
                   System.out.println(e.getMessage());
                   }

Now , use update query to update the votes like below :

String sql1 = "UPDATE `Total_Votes` SET `yourcoulumnname`=? WHERE `team`=?";
             PreparedStatement ps = con.prepareStatement(sql1);
            int v=votes+1;//votes got from previous select query add by 1 
             ps.setInt(1,v);
             ps.setString(2,"team1");

             int i=0;
              i = ps.executeUpdate();

         if(i>0){
             System.out.println("updated");
           }

Hope this helps you !

Upvotes: 1

Jason
Jason

Reputation: 11832

Your code is always writing 1 as the total votes value for the specified team. That's fine if you use a SUM() function in SQL to total up the vote counts for a team when you need to know the total.

There are two other ways to handle this:

  1. Only ever have one record in the database per team. Each time a vote comes in, read the current value (or assume 0 if you can't find a current value), increment it and then UPDATE the record with the new value.

  2. Keep inserting a record per vote. Each time a vote comes in, read the current MAX() value (or assume 0 if you can't find a current value), increment it and INSERT another record with the new value.

Upvotes: 1

Related Questions