I wrote a C# function that saves coupon usage information to the database. Here’s what I have:
public async Task<bool> RecordCouponUsageAsync(string couponCode, int userId)
{
try
{
string query = "INSERT INTO CouponUsage (UserID, DiscountID, UsageTimestamp) "
+ $"SELECT {userId}, ID, GETDATE() "
+ $"FROM Discounts WHERE Code = '{couponCode}'";
await _dbService.RunQueryAsync(_config.ConnectionString!, query);
return true;
}
catch
{
return false;
}
}
I got some advice about using parameterized queries to make this safer. The couponCode value comes directly from what users type in. Should I be worried about security issues here? What would be the best approach to protect against potential attacks while keeping the same functionality?
Oh wow, this brings back memories! Quick question though - have you tested what happens if someone enters malicious code in that couponCode field? Like '; DROP TABLE CouponUsage; -- or similar SQL injection attempts? Curious how your setup handles that stuff.
Your code’s wide open to SQL injection attacks. Concatenating strings directly with couponCode is dangerous - attackers can run whatever SQL they want. I’ve been burned by this exact issue in production before. Fix is simple: use parameterized queries instead. Change your query to WHERE Code = @couponCode and pass the value through your database service’s parameter collection. User input gets properly sanitized and treated as data, not executable code. You keep the same functionality but kill the security risk.
for sure, you gotta be cautious! your approach can be exploited real easy. using parameterized queries is the way to go, it’ll help keep your data safe from those sql injections. trust me, it’s a must!