这是我的代码,它从数据库中检索信息,并在表格中显示一个附加按钮,该按钮将用于提交(添加到fav)到另一个新表,其中包含该行的值和用户ID以下代码正确显示所有记录在表中,每一行都包含在一个带有按钮的表单中,所以当我点击一个特殊的行按钮时,那行的值只应传递给目标页面,但是对于每一行,只有第一个记录值正在传递..
<%pst = con.prepareStatement("select * from reg_faculty");
res = pst.executeQuery();
while(res.next()) {
String uname = res.getString(1);
String id = res.getString(2);
String branch = res.getString(5);
String subject = res.getString(4);
%>
<tr><td align="center"><b><%=uname%></b></td><td align="center"><b><%=branch%></b></td>
<td align="center"><b><%=subject%></b></td>
<input type="hidden" name="fac_id" value="<%=id%>">
<input type="hidden" name="std_id" value="<%=ht%>">
<input type="hidden" name="fac_name" value="<%=uname%>">
<td align="center"><img src="viewimagef.jsp?id=<%=id%>&type=<%="faculty"%> " alt="" width="100" height="60" /></td>
<td align="center"><input type="submit" value="Add"/></td>
</tr>
<%
}
%>
目标页面,其中所选行值应传递给数据库,但对于所选的任何行,第一个记录值都将传递
String std_id1=request.getParameter("std_id");
String fac_id2=request.getParameter("fac_id");
String name=request.getParameter("fac_name");
try{
pst=con.prepareStatement("select * from fav_faculty where std_id=? AND fac_id=?");
pst.setString(1, std_id1);
pst.setString(2, fac_id2);
res=pst.executeQuery();
boolean exists = false;
if(res.next()){
out.println("Faculty Already exist in your List");
out.println("Faculty: "+fac_id2+" Student Id: "+std_id1+" Name: "+name);
}else{
pst=con.prepareStatement("insert into fav_faculty values(?,?)");
pst.setString(1, std_id1);
pst.setString(2,fac_id2);
int j=pst.executeUpdate();
if(j>0){
out.println("You successfully added "+name+" to your Faculty List");
}
}
}catch (Exception e) {
out.println("Unable To Add");
}
答案 0 :(得分:0)
问题在于您正在使用的提交按钮,提交按钮属于整个表单,工作方案会将提交按钮的值更改为教师ID,但保留所有提交按钮的相同名称。 另一个可能更好的解决方案是添加复选框而不是提交按钮。
<tr><td align="center"><b><%=uname%></b></td><td align="center"><b><%=branch%></b></td>
<td align="center"><b><%=subject%></b></td>
<input type="hidden" name="fac_id" value="<%=id%>">
<input type="hidden" name="std_id" value="<%=ht%>">
<input type="hidden" name="fac_name" value="<%=uname%>">
<td align="center"><img src="viewimagef.jsp?id=<%=id%>&type=<%="faculty"%> " alt="" width="100" height="60" /></td>
<td align="center"><input type="ckeckbox" name="fac_id" value="<%=id%>">
</tr>
%><%-- end of the while loop --%>
<input type="submit" value="add all">
并在目标网页
中String allSelectedFacultyIds[]= request.getParameterValues("fac_id");
for (int i=0;i<allSelectedFacultyIds.length;i++)
{
pst=con.prepareStatement("select * from reg_faculty where id="+allSelectedFacultyIds[i]);
//now you have the name, id, ... so the rest of your code should apply with minor changes
}