Silver Archer Silver Archer - 1 month ago 5
ASP.NET (C#) Question

Double data insert into database asp.net c#

I am doing airline reservation system. When I insert all the data into database, it insert double data. Why is this happened ?
This is my code:

public partial class CompleteOrder : System.Web.UI.Page
{
string SeatNum;
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-28L03QE\SQL2014;Initial Catalog=Airline;Integrated Security=True;Pooling=False");
con.Open();

Random rnd = new Random();
int ordernum = rnd.Next(3, 10000);
string Name = Request.QueryString["name"];
string IC = Request.QueryString["ic"];
string Contact = Request.QueryString["contact"];
string SeatType = (string) (Session["seats"]);
SeatNum = Request.QueryString["seatnum"];

Label7.Text = Convert.ToString(ordernum);
Label4.Text = Name;
Label8.Text = IC;
Label10.Text = Contact;
Label14.Text = SeatType;
Label16.Text = SeatNum;



SqlCommand cmd = new SqlCommand("INSERT INTO [Table](OrderNum,Name,IdentificationNumber, ContactNumber, SeatType, SeatNumber)VALUES('" + Label7.Text + "','" + Label4.Text + "','" + Label8.Text + "','" + Label10.Text + "', '" + Label14.Text + "', '" + Label16.Text + "')", con);
cmd.ExecuteNonQuery();
con.Close();
}

protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Response.Redirect("~/Main.aspx?seatnum="+SeatNum);
}
}


Please help me, thank you.

Answer

You have two bad practices going on here.

First, you should use sql parameters instead of simply concatenating them; to avoid SQL injection. Read here.

Second, don't do an insert in a HTTP GET (Page_Load). You should do this in a HTTP POST and then redirect to an HTTP GET again (PRG pattern).

The reason of the double insert may be because you hit the same page twice (Page_Load in this case); something you would have noticed if you apply the PRG pattern.

See Post-Redirect-Get with ASP.NET.