Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
First of all, I am not really into hard coding and such, I really did try to search for a solution to my problem but I am not getting some of the explanation. Or maybe it is not the way I code mine so I cannot understand.

Technically I have 3 lisboxes for the quantity, product name, and price of the product. When a product is added on a cart, it automatically lists down in the listbox.

I am trying to subtract the quantity of the product stocks saved in the database, to the number of products listed on the cart.

My code works when I only buy one product, but when I am trying to buy 2 or more products, nothing gets subtracted to the database of my products.

PS. Sorry if ever I incorrectly posted my question, it is just my first time posting here. Thank you in advance!

What I have tried:

C#
string item = string.Empty;
int quantity = 0;

for (int i = 0; i <= LBItemName.Items.Count - 1; i++)
{
    item += Convert.ToString(LBItemName.Items[i]);
}

for (int j = 0; j <= LBItemQuantity.Items.Count - 1; j++)
{
    quantity += Convert.ToInt32(LBItemQuantity.Items[j]);
}

MySqlCommand tryCommand = new MySqlCommand("UPDATE QuizonVet.Product SET
    numberofstocks = (numberofstocks - '" + quantity + "') where productname='" + 
    quantity + "';", myConnection);

myReader = tryCommand.ExecuteReader();
myReader.Close();
Posted
Updated 19-Dec-17 20:58pm

1 solution

C#
MySqlCommand tryCommand = new MySqlCommand("UPDATE QuizonVet.Product SET numberofstocks = (numberofstocks - '" + quantity + "') where productname='" + quantity + "';", myConnection);

One can suspect quantity is not the productname.

Not a solution to your question, but another problem you have.
Never build an SQL query by concatenating strings. Sooner or later, you will do it with user inputs, and this opens door to a vulnerability named "SQL injection", it is dangerous for your database and error prone.
A single quote in a name and your program crash. If a user input a name like "Brian O'Conner" can crash your app, it is an SQL injection vulnerability, and the crash is the least of the problems, a malicious user input and it is promoted to SQL commands with all credentials.
SQL injection - Wikipedia[^]
SQL Injection[^]
SQL Injection Attacks by Example[^]
PHP: SQL Injection - Manual[^]
SQL Injection Prevention Cheat Sheet - OWASP[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900