-6

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.

Silver Archer
  • 167
  • 3
  • 3
  • 14

2 Answers2

1

It might be after clicking image button. Because first data is inserted on page load and second after postback happened due to image button click. You can avoid this by keeping insert logic inside

if(!Page.IsPostBack)
{
    // insert code
}

Still I am confused why you are inserting data on page load. Someone can fill you database too much to annoy you.

Imad
  • 7,126
  • 12
  • 55
  • 112
0

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.

Community
  • 1
  • 1
L-Four
  • 13,345
  • 9
  • 65
  • 109