Skip to content Skip to sidebar Skip to footer

Loop Insert Problem, Reload Page Load?

Im trying to achieve an insert statment and return using my function in the pageload. Not sure how I can insert at the same time draw what i inserted into mysql back out again all

Solution 1:

First of all, move the code that populate the element with the wall posts to separate function:

privatevoidPopulateWallPosts(string userId)
{
    using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=user_name; Password=password_here;"))
        {
        cn.Open();
        using (OdbcCommand cmd = new OdbcCommand("SELECT Wallpostings FROM WallPosting WHERE UserID=" + userId) + " ORDER BY idWallPosting DESC", cn))
        {
            using (OdbcDataReader reader = cmd.ExecuteReader())
            {
                var divHtml = new System.Text.StringBuilder();
                while (reader.Read())
                {
                    divHtml.Append("<div id=test>");
                    divHtml.Append(String.Format("{0}", reader.GetString(0)));
                    divHtml.Append("</div>");
                }
                test1.InnerHtml = divHtml.ToString();
            }
        }
    }
}

Now call this in Page_Load:

protectedvoidPage_Load(object sender, EventArgs e)
{
    string theUserId = Session["UserID"].ToString();
    PopulateWallPosts(theUserId);
}

And finally call it after inserting the new value:

protectedvoidButton1_Click(object sender, EventArgs e)
{
    string theUserId = Session["UserID"].ToString();
    using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=user_name; Password=password_here;"))
    {
        cn.Open();
        using (OdbcCommand cmd = new OdbcCommand("INSERT INTO WallPosting (UserID, Wallpostings) VALUES (" + theUserId + ", '" + TextBox1.Text + "')", cn))
        {
            cmd.ExecuteNonQuery();
        }
    }
    PopulateWallPosts(theUserId);
}

Your commented code didn't work because you executed the INSERT INTO command again instead the SELECT command.

Anyway, you really better learn about SQL Injection and change your code to use Parameters instead of directly adding the user ID to the SQL string.

Post a Comment for "Loop Insert Problem, Reload Page Load?"