简体   繁体   中英

insert statement wont work

Hey guys I get no errors from my code but nothing seems to happen when i try my insert statement below?
Not sure if its how I wrapped my textbox or if its my FriendID query string?

    protected void Button1_Click(object sender, EventArgs e)
    {
        string friendid = Request.QueryString["FriendID"];
        string theUserId = Session["UserID"].ToString();
        using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=***; User=***; Password=***;"))
        {
            cn.Open();
            using (OdbcCommand cmd = new OdbcCommand("INSERT INTO WallPosting (UserID, Wallpostings, FriendUserID) VALUES (" + friendid + ", '" + TextBox1.Text + "', " + theUserId + ")", cn))
            {
                cmd.ExecuteNonQuery();
            }
        }
        PopulateWallPosts(friendid);
    }
}

You switched your variables, according to the field names it should be:

using (OdbcCommand cmd = new OdbcCommand("INSERT INTO WallPosting (UserID, Wallpostings, FriendUserID) VALUES (" + theUserId + ", '" + TextBox1.Text + "', " + friendid  + ")", cn))

New record has been added, but for the wrong user so you didn't find it later when reloading the posts.

As you've been told already deal with the SQL Injection risk by using Parameters instead of directly adding the values to the SQL string.

"INSERT INTO WallPosting (UserID, Wallpostings, FriendUserID) VALUES (" + friendid + ", '" + TextBox1.Text + "', " + theUserId + ")"

becomes

"INSERT INTO WallPosting (UserID, Wallpostings, FriendUserID) VALUES ('" + friendid + "', '" + TextBox1.Text + "', '" + theUserId + "')"

Have to qualify the strings using single quotes. otherwise they are treated as variables by the parser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM