BONIETTE
BONIETTE

Reputation: 27

save the changes from JSP table into the database

I have a table which displays the content of a database. I want to save the changes edited in the table to my database. The problem is no matter what row I edit, each time when I try to save, it takes as parameters the values from the first row.

Main.jsp:

<FORM NAME="form1" METHOD="POST" action="update.jsp">
    <table>
        <% ResultSet rs=statement.executeQuery(query);
        while(rs.next())
        {%>
            <tr>
                <td style="display:none;"><input type="text" name="id" value="
                <%=rs.getInt("ID") %>"></td>
                <td><input type="text" name="val1" value="<%=rs.getString("Value1") %>"></td>
                <td><input type="text" name="val2" value="<%=rs.getString("Value2") %>"></td>
                <td><input type="submit" name="Submit" value="Save"></td>
            </tr>
        <% } %>
    </table>
</FORM> 

update.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*,java.io.*,java.util.*,dbcon.SQLConnection" %>
<% String idRez=request.getParameter("id");
    String v1=request.getParameter("val1");
    String v2=request.getParameter("val2");
    SQLConnection.updateDatabase(idRez,Double.parseDouble(v1), Double.parseDouble(v2));
    response.sendRedirect("Main.jsp");
%>

Upvotes: 0

Views: 947

Answers (1)

Pradeep Pati
Pradeep Pati

Reputation: 5919

Since all the rows in your Main.jsp have the same name(id, val1, val2), whenever you do a request.getParamater() call, the 1st matching parameter will be returned.

You can fix this by fetching all the parameter values as follows.

String[] ids = request.getParameterValues("id");

You will have to modify your Main.jsp accordingly to make sure you fetch the correct combination of values in update.jsp

However, as you only want to submit the row on which you are clicking Save, you can declare Form on the row instead of having a Global Form.

<!--FORM NAME="form1" METHOD="POST" action="update.jsp"-->
    <table>
        <% ResultSet rs=statement.executeQuery(query);
        while(rs.next())
        {%>
            <tr>
                <td style="display:none;">
                <FORM NAME="form1" METHOD="POST" action="update.jsp">
                <input type="text" name="id" value="
                <%=rs.getInt("ID") %>"></td>
                <td><input type="text" name="val1" value="<%=rs.getString("Value1") %>"></td>
                <td><input type="text" name="val2" value="<%=rs.getString("Value2") %>"></td>
                <td><input type="submit" name="Submit" value="Save"></FORM></td>
            </tr>
        <% } %>
    </table>
<!--/FORM--> 

Upvotes: 1

Related Questions