Summary: I implemented a search functionality using ajax and JSP,it was working well.Then,I wanted to give a message if the search term cannot be found like "No record found".I put an if statement in my code and it seemed to work.I later realized the if statement was truncating some of my results from the database for example,if I type t(without the if statement),it gives me about 9 records,but with the if statement it gives me like 8 records,which is not meant to be so.I have been working on this for a long time,but I couldn't just get the problem.
For clarity,Screenshot without if statement
Screenshot with if statement included
This the code that does the search and displays it:
<table align="center">
<%@page import="java.sql.*" %>
<%
Connection con;
PreparedStatement ps;
ResultSet rs;
String query;
String se = request.getParameter("se");
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/alumni", "root", "root");
query = "Select * from users where un like '" + se + "%' or fn like '"+se+"%' or ln like '"+se+"%' ";
ps = con.prepareStatement(query);
rs = ps.executeQuery();
//if statement that seems to be causing the problem.
if(rs.next()){
}else{
out.println("No record found for "+se);
return;
}
int k = 0;
while (rs.next()) {
k++;
%>
<tr>
<td class="go" style="width: 608px;border-radius: 6px; height: 44px;">
<a href= 'profile.jsp?un=<%=rs.getString("un")%>' style="text-decoration: none; ">
<div class="search" >
<!-- image -->
<script>
function imgError(image) {
image.onerror = "";
image.src = "images/avatar.jpg";
return true;
}
</script>
<% out.println("<img onerror='imgError(this)' width = 65 height = 55 style='border-radius:5px' src=picView?un=" + rs.getString("un") + ">"
+ "</img>");%>
<div style="display: inline;"> <%=rs.getString("un")%> </div>
<div style="display: inline-block;">
<%=rs.getString("fn")%> <%=rs.getString("ln")%> </div>
</div> </a>
</td>
</tr>
<%
}
}
catch (Exception e) {
out.println("Exception "+e);
}
%>
Please note:The if statement was put there to inform the user if a record is not found and it performs its function well. I understand I shouldn't use scriptlets,but I used it due to some reasons.Please bear with me. Thanks.