Silver Archer Silver Archer - 1 year ago 96
ASP.NET (C#) Question

Double data insert into database 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");

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);

protected void ImageButton1_Click(object sender, ImageClickEventArgs e)

Please help me, thank you.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download