Hello I am creating a web page to add some information about given product.I need to enter id,name,description and image as information.I need the id to be auto generated.I am using jsp and database as access.I am fetching the count(*)+1 value from database and assigning to my html text box but its showing as null.can i get some help?
Code:
<body>
<%#page import="java.sql.*"%>
<%! String no; %>
<%
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:pd");
ResultSet rs = null;
Statement st = con.createStatement();
String sql = ("select count(*)+1 from products");
st.executeUpdate(sql);
while (rs.next()) {
no=rs.getString("count(*)+1");
}
rs.close();
st.close();
con.close();
}
catch(Exception e){}
%>
<Form name='Form1' action="productcode.jsp" method="post">
<table width="1024" border="0">
<tr>
<td width="10"> </td>
<td width="126">Add Product: </td>
<td width="277"> </td>
<td width="583"> </td>
</tr>
<tr>
<td> </td>
<td>Product Id:</td>
<td><label>
<input type="text" name="id" value="<%= no%>"/>
</label></td>
<td> </td>
.... and so on
{..}.executeQuery("Select max(id) from tablename");
This will return the ID with the largest number. Its more efficient than select * from tablename order by id desc limit 1.
However, it looks like your trying to guess/generate an ID of an object which doesn't yet exist in the database. This isn't the best way, and you may find that the ID your generating may be different to that generated by your DB. It could also cause duplication errors if two people are trying to create two new objects at the same time.
I would suggest that you don't provide a product id until the "create product" button has been pressed. Use ##IDENTITY; in your SQL command to set the new ID to your product safely.
You wrote a query to get the data like this
String sql = ("select count(*)+1 from products");
st.executeUpdate(sql);
The statement
executeUpdate()
only used to do the operations like INSERT,UPDATE
try
rs=st.executeQuery(sql);
instead of executeUpdate()
Related
I have a small problem. Right now I'm programming a website, which is connected to a mysql database.
I created a table filled with products, which are stored in the database. Each row has a Button "Add to Cart" but how do I exactly get the specific item for it? I already have the function addtoCart(string articleName) but I don't know how to get the name of the product.
This is what I've got so far:
<table id="Products">
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Stock</th>
</tr>
<%
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop", "root", "12345");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT* FROM products WHERE category='shisha'");
while(rs.next()){
int id = rs.getInt("articleID");
String pname = rs.getString("productName");
String description= rs.getString("description");
float price = rs.getFloat("price");
int stock = rs.getInt("stock");
%>
<tr>
<td><%out.print(id);%></td>
<td><%out.print(pname);%></td>
<td><%out.print(description);%></td>
<td><%out.print(price);%></td>
<td><%out.print(stock);%></td>
<td> </td>
<td><input type="text" placeholder="How much ?" name="quantity" required> </td>
<td> <input class="button" type = "submit" value="Add to cart"> </td>
</tr>
<%
}
%>
</table>
So it generates a row for each product with its own button.... I want to call the function addtoCart(string articleName) but how do I get the product name of the row the button is in?
Using Jquery you could add a class and data attribute to your button, you could then get the value like so.
<input class="button" data-product="<%out.print(pname);%>" type = "submit" value="Add to cart">
$('.button').click(function(){
var product = $(this).data("product");
addtoCart(product);
});
I hope this helps.
Thanks
add it to the button. Instead of making the button a submit button, create a
<button onclick="addToCart(%out.print(id);%);">Add to cart</button>
then get the product information in a function called addToCart
In this project, I would like to get a date from data that user just input using form using JSP. After that, I would like to store the input to MySQL.
This is my JSP file:
<form:form id="regForm" modelAttribute="assignment" action="successAddAssignment" method="post">
<table align="center">
<tr>
<td>
<form:label path="date">Date</form:label>
</td>
<td>
<form:input path="date" name="date" type="date" id="date" pattern="yyyy/MM/dd"/> <span class="inst">(YYYY-MM-DD)</span>
</td>
</tr>
<tr>
<td></td>
<td>
<form:button id="addAssignment" name="addAssignment">Submit</form:button>
</td>
</tr>
<tr></tr>
</table>
</form:form>
This is my Dao file :
public void addAssignment(Assignment assignment){
String sql = "insert into assignment values(?,?,?,?,?,?)";
jdbcTemplate.update(sql, assignment.getId(), assignment.getDate(), assignment.getTime(), assignment.getCode_module(), assignment.getName_module(), assignment.getDescription());
}
But, when I run my program, the result is like this:
1
I got an error when I want to submit the data "date". My question is How do I create the date format from "yyyy/MM/dd" to "dd/MM/yyyy"?
There is no pattern tag in JSP. You probably need to convert a string into a Date object with JS or in the controller.
Something like this may work in the controller:
String dateReceived = "2018-04-24";
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date dateFormatted = dateFormat.parse(dateReceived);
You may want to check SimpleDateFormat
I have an ASP page which displays rows of data in an HTML table, after a query to an SQL database. The number of returned rows can vary. I want to add a function so that when i click on a button, I fire off a query to the SQL server database to update a column in that particular row. To do that i will use the primary key from my result set.
The part I am having difficulty with is getting the proper rows ID. What I have wrote so far returns the same ID every time regardless of which row i click on. Sample code below.
<table>
<tr>
<td class="bold" colspan="9"><%=vHeading%></td>
</tr>
<tr>
<td class="tablehead">Id</td>
<td class="tablehead">WhenPosted</td>
<td class="tablehead">WhenCreated</td>
<td class="tablehead">WhenUpdated</td>
<td class="tablehead">Source</td>
<td></td>
</tr>
<%
DO WHILE NOT stRs.eof
i = i + 1
%>
<tr>
<td id="pId<%=i%>" class="tablecell"><%=stRs.fields("Id")%></td>
<td class="tablecell"><%=stRs.fields("WhenPosted")%></td>
<td class="tablecell"><%=stRs.fields("WhenCreated")%></td>
<td class="tablecell"><%=stRs.fields("WhenUpdated")%></td>
<td class="tablecell"><%=stRs.fields("Source")%></td>
<td id=<%=i%>><input type="button" value="Post" onclick="post();" /></td>
</tr>
<%
stRs.MoveNext
LOOP
%>
</table>
<script text="text/javascript">
function post() {
var pId = document.getElementById("pId").innerHTML;
alert(pId);
}
</script>
So i loop through my result set creating rows. For examples-sake, row one will contain ID 1. Row 2 will have ID 2 etc.
If I click on my button which fires off the post method, the alert shows ID 1 every time, no matter the row i click on. I guessed its because i was originally assigning the same ID to the column for each row. I now use a counter variable and assign it to the ID which is creating unique ID's for the columns now, but I'm not sure how to call the function and use the correct ID. Any pointers are much appreciated!
You have to pass I to the function:
<input type="button" value="Post" onclick="post(<%=i%>);" />
then
<script text="text/javascript">
function post(i) {
var pId = document.getElementById("pId"+i).innerHTML;
alert(pId);
}
</script>
I am new to Java and programming in general. For background, I am working on my simple survey system. I have all the classes/methods necessary to insert and pull from MySQL and display the survey on my JSP page.
This is my Index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Survey System</title>
</head>
<body>
<h1>Survey List</h1>
<%
ResultSet resultset = new controller.SelectSurvey().SelectSurvey();
if (request.getParameter("btnControlSurvey") != null){
response.sendRedirect("controlsurvey.jsp");
}
if (request.getParameter("btnTakeSurvey") != null){
response.sendRedirect("takesurvey.jsp");
}
%>
<form name = 'surveylist' action="index.jsp" method="POST">
<table border="0">
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select id="listsurvey">
<% while (resultset.next()) {
%>
<option><%= resultset.getString("survey_ID")%> - <%= resultset.getString("title")%></option>
<% } %>
</select>
</td>
<td>
<input type="submit" value="TAKE SURVEY" name = "btnTakeSurvey" />
</td>
</tr>
</tbody>
<td>
<input type="submit" value="CONTROL SURVEY" name = "btnControlSurvey" />
</td>
</table>
</form>
</body>
How do I pass the selected surveyID value in my drop down list with ID listsurvey to my hard-coded surveyID1 variable in my Takesurvey.jsp (see below) once the Submit button is clicked?
<%
int surveyID1 = 1;
ResultSet rsSurvey = new controller.SelectSurvey().SelectSurveyByID(surveyID1);
ResultSet rsSurveyQuestion = new controller.SelectSurvey().SelectQuestionByID(surveyID1);
%>
I found that there are at least three ways to do this as listed below. What would be the easiest way and would you please give me an example?
Putting values into the session object.
Putting values into the application object
Putting values at the end of the redirect URL.
Your inputs are very appreciated.
Thank you and have a good day.
Not sure what you're doing in that 2nd code segment, but you can get a hold of the form parameters using
String surveyId = request.getParameter(listsurvey);
It looks like you're looking for an int on the other side, but it comes in as a String so just use Integer.parseInt() after you pull it from the request.
Note: The request variable is already implicitly available in your JSP. You don't have to declare it.
http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameter%28java.lang.String%29
You need to pass the surveyID in the HTTP page request using either GET or POST. Then in the servlet / JSP you can use request.getParameter("surveyID")
I figured it out by using request.getParameters and use different forms for each button and it works as wanted.
Thank you for all of yours input again guys.
I have aproblem. Here I am showing some bills from Invoice table in mysql. And for single bill I am keeping a checkbox. I want to pass selected checkbox values to next jsp page. Please help me to do it. Thanks in advance.
<%
String company_name=request.getParameter("c_name");
try
{
Integer count=0;
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","aadi");
Statement st = con.createStatement();
String sql="select invoice_no, invoice_date, gross_amount from tbl_invoice where client='"+company_name+"'";
ResultSet rs=st.executeQuery(sql);
%>
<center>
<table id="show_table">
<tr>
<td>PNR No</td>
<th>Date</td>
<th>Amount</td>
<th>Select</td>
</tr>
<%
while(rs.next())
{
%>
<tr>
<td><%=rs.getInt(1)%></td>
<td><%=rs.getString(2)%></td>
<td><%=rs.getInt(3)%></td>
<td><input type="checkbox" name="ck"/></td>
</tr>
%>
</table>
</center>
<%
}
catch(Exception e)
{
out.println(e);
}
%>
Hey I found the solution. On action page where I am going to receive values I will store all checkbox names in a array of string.
String selected_Checkboxes=request.getParameterValues("ck");
I will just change "td" tag of checkbox. I will put value of PNR NO which is coming from database and will put in checkbox.
<td><input type="checkbox" value="<%=rs.getInt(1)%>" name="ck"/></td>
I will use indexes of "selected_Checkboxes" to do further coding.
--Thanks Santino 'Sonny' Coleone