Reputation: 33
I'm trying to create an sql search that will filter posts depending on the username stored in the string variable. I'm having issues with formatting it correctly and was wondering if anyone could help or tell me what i'm doing wrong.
foreach (var getrow in DB.Query("Select * from Posts where Username=" + username)
Upvotes: 0
Views: 107
Reputation: 542
Does this help?
"Select * from Posts where Username='" + username + "'"
REFER TO SOLUTIONS BELOW. Note Ahmed's comment below ref SQL injection.
Upvotes: 1
Reputation: 15860
You're more likely to be using Parameters in ASP.NET while trying to create a Connection to Database. It reduces the Risk of being attacked by an Hacker.
What you should try would be the following
foreach (var getrow in DB.Query(
"SELECT * FROM Posts WHERE Username =@0", username);
Furthermore, go to https://en.wikipedia.org/wiki/SQL_injection to learn more about SQL Injection and the ways you can use to prevent it.
Upvotes: 0
Reputation: 18769
I think a better way is...
var sql = "SELECT * From Posts WHERE username = @0"
...and then use DB.Query(sql, username)
This will help prevent sql injection attacks
Upvotes: 1