-1

I am using ASP.NET with the Webpages model and have created a database for users to post to, which is all great, then I created a page so users can edit their posts, however I want it so users can only edit their own posts.

To do this, I tried the following:

I made a variable

var EmailMatch = WebSecurity.CurrentUserName;

so if I put @EmailMatch anywhere in the html markup it will display the email address of the user who is currently logged in. Now in order to display only the posts that this user has made, I used this select statement:

var selectAllString = "SELECT * FROM SaleData WHERE Email = '@EmailMatch'";

In theory I am thinking this should work, because when the user makes a post it sends their email address to the database under the field 'Email' and it should display records that are equal to the user currently logged in. However this statement returns 0 results, I have tried all I can think of with no success, this is my last resort, can someone please tell me what I am missing? Thanks in advance..

4

4 回答 4

4

正确的方法是通过参数化查询。永远不要将您无法控制的字符串连接到查询中。

var EmailMatch = WebSecurity.CurrentUserName;
var selectAllString = "SELECT * FROM SaleData WHERE Email = @EmailMatch";
SqlCommand cmd = new SqlCommand(s);
cmd.Parameters.Add("@EmailMatch", EmailMatch);
var resultsTable = cmd.ExecuteReader();
于 2012-12-26T03:14:53.617 回答
1

尝试这个:

var selectAllString = "SELECT * FROM SaleData WHERE Email = '"+EmailMatch+"'";

或者为了避免 SQL 注入,你的 SQL 语句是正确的,但你必须在你的代码中添加这个:

using (OleDbConnection CON = new OleDbConnection("your connection string")) {
   OleDbCommand Com = CON.CreateCommand();
   Com.CommandText = "SELECT * FROM SaleData WHERE Email = @EmailMatch";
        Com.CommandType = CommandType.Text;
        Com.CommandTimeout = 0;
        Com.Connection.Open();
        Com.Parameters.AddWithValue("EmailMatch",EmailMatch);
   ...
   // continue your code from here... 
}
于 2012-12-26T03:07:12.133 回答
1
var selectAllString = "SELECT * FROM SaleData WHERE Email = '" + EmailMatch + "'";

Note: This could possibly expose you to SQL Injection attacks.

于 2012-12-26T03:07:00.697 回答
1
cmd = new MySqlCommand("SELECT * FROM SaleData WHERE Email = @EmailMatch", MySqlConn.conn);
cmd.Parameters.AddWithValue("@EmailMatch", EmailMatch);
cmd.Prepare();
cmd.ExecuteReader();
于 2012-12-26T03:22:12.547 回答