I have written the code below for adding products to a basket, then outputting them as well as making multiple requests to the server to insert and select data.
I posted a question yesterday about assigning the result of an SQL command to a variable but nothing seems to work, probably due to the code I have written, if there is a solution for this I would be very grateful.
Also is there anyway to simplify the SQL commands I seem to be making quite a few
I know about the vulnerability for SQL injection attacks, this is just a Uni project and I doubt the lecturer even knows about them! Nevertheless I will sort these out once I get the basic functionality working 🙂
string CurrentUser="";
if (User.Identity.IsAuthenticated) {
CurrentUser = Membership.GetUser(HttpContext.Current.User.Identity.Name).ProviderUserKey.ToString(); //Get the current user
}
//Insert the current user into the DB
BasketPage.InsertCommand = "INSERT INTO tblBasket(UserID, CreatedDate) VALUES ('" + CurrentUser + "'), CONVERT (DATETIME, '2010-11-20 00:00:00', 102))";
//Select the Basket ID for this user which is an auto increment hence why I inserted the user first
BasketPage.SelectCommand = "SELECT BasketID FROM tblBasket WHERE (UserID = '" + CurrentUser + "')";
var basketID= //Result of the previous select command
if (Session["CartSess"] != null) {
List<BasketClass> cart = (List<BasketClass>)Session["CartSess"];
foreach (BasketClass BookID in (List<BasketClass>)Session["CartSess"]) {
BasketPage.InsertCommand = "INSERT INTO tblBasketDetails(BasketID, BookID) VALUES (" +
basketID + "," + BookID + ")"; //Inserts each book into the DB and the Basket ID
BasketPage.Insert();
}
}
//Outputs the Basket for the current user
BasketPage.SelectCommand = "SELECT tblBasket.UserID, tblBasket.BasketID, tblBooks.Title, tblBasketDetails.Quantity " +
"FROM tblBasket " +
"INNER JOIN tblBasketDetails ON tblBasket.BasketID = tblBasketDetails.BasketID " +
"INNER JOIN tblBooks ON tblBasketDetails.BookID = tblBooks.BookID " +
"WHERE (tblBasket.UserID = '" + CurrentUser + "')";
On the line:
Substituting ‘SomeValue’ for your CurrentUser variable, your SQL is:
Try running that in a SQL window. In SQL Server You’ll get:
Your problem is with the first clsing bracket on the VALUES LINE. The code should be:
As a general bit of advise, try testing your queries standalone before runing them as part of your code.
Casting aside the SQL Injection problems that you mentioned, this is another reason for moving all your code to a stored procedure and calling it with parameters from your code.