user1901907
user1901907

Reputation: 33

SQL search using string variable

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

Answers (3)

Johnny Fitz
Johnny Fitz

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

Afzaal Ahmad Zeeshan
Afzaal Ahmad Zeeshan

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

Christian Phillips
Christian Phillips

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

Related Questions