Click here to Skip to main content
15,063,183 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to perform an upsert command on 'edit account' page where users can edit their information. When a user logs in, they will be redirected to a 'My Account' page which will display all their information.

The edit account page will be accessing/inserting data into 3 tables: Member, Address and Address_Member.

When I perform an insert command, new data was inserted but I do not know how to insert the IDs into the Address_Member table where the information are linked with each other and eventually display on my account page.

I also received this error: System.Data.SqlClient.SqlException (0x80131904): Must declare the scalar variable "@AddressID"

What I have tried:

1. Member

SQL
CREATE TABLE [dbo].[Member]
( [MemberID] INT IDENTITY (1, 1) NOT NULL,
[MemberName] VARCHAR (30) NOT NULL,
[Phone] BIGINT NOT NULL,
[Email] VARCHAR (50) NOT NULL,
[Username] VARCHAR (50) NOT NULL,
[Password] NCHAR (30) NOT NULL,
PRIMARY KEY CLUSTERED ([MemberID] ASC) );

2.Address
SQL
CREATE TABLE [dbo].[Address]
( [AddressID] INT IDENTITY (1, 1) NOT NULL,
[HouseNumber] VARCHAR (10) NOT NULL,
[AddressLine1] VARCHAR (30) NOT NULL,
[AddressLine2] NCHAR (30) NOT NULL,
[City] NCHAR (20) NOT NULL,
[PostCode] NCHAR (7) NOT NULL,
[AddressType] NVARCHAR (MAX) NOT NULL,
PRIMARY KEY CLUSTERED ([AddressID] ASC) );

3.Address_Member
SQL
CREATE TABLE [dbo].[Address_Member]
( [MemberID] INT NOT NULL,
[AddressID] INT NOT NULL,
PRIMARY KEY CLUSTERED ([MemberID] ASC, [AddressID] ASC),
CONSTRAINT [FK_Address_Member_Address] FOREIGN KEY ([AddressID]) REFERENCES [dbo].[Address] ([AddressID]), CONSTRAINT [FK_Address_Member_Member] FOREIGN KEY ([MemberID]) REFERENCES [dbo].[Member] ([MemberID]) );

The following is the code in editaccount.aspx.cs:
C#
public partial class EditAccount : System.Web.UI.Page
{
    public SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True");

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SqlCommand com;
            string str;

            conn.Open();
            str = "SELECT Address.HouseNumber, Address.AddressLine1, Address.AddressLine2, Address.City, Address.PostCode, Address.AddressType, Address_Member.MemberID, Address_Member.AddressID, Member.MemberName, Member.Phone, Member.Email, Member.Username FROM Address INNER JOIN Address_Member ON Address.AddressID = Address_Member.AddressID RIGHT JOIN Member ON Address_Member.MemberID = Member.MemberID WHERE Member.Email = '" + Session["Email"] + "'";
            com = new SqlCommand(str, conn);
            SqlDataReader reader = com.ExecuteReader();

            if (reader.Read())
            {

                TxtEName.Text = reader["MemberName"].ToString();
                LblEUser.Text = reader["Username"].ToString();
                TxtEEmail.Text = reader["Email"].ToString();
                TxtEPhone.Text = reader["Phone"].ToString();
                TxtEType.Text = reader["AddressType"].ToString();
                TxtEHouse.Text = reader["HouseNumber"].ToString();
                TxtEA1.Text = reader["AddressLine1"].ToString();
                TxtEA2.Text = reader["AddressLine2"].ToString();
                TxtECity.Text = reader["City"].ToString();
                TxtEPostcode.Text = reader["PostCode"].ToString();

                reader.Close();
                conn.Close();
            }
        }

    }

    protected void BtnSave_Click(object sender, EventArgs e)
    {
        SqlDataAdapter adapter;

        DataTable dt = new DataTable();
        DataTable dadt = new DataTable();
        DataTable da = new DataTable();



        try
        {
            conn.Open();
            string query = "SELECT Address.HouseNumber, Address.AddressLine1, Address.AddressLine2, Address.City, Address.PostCode, Address.AddressType, Address_Member.MemberID, Address_Member.AddressID, Member.MemberName, Member.Phone, Member.Email, Member.Username FROM Address INNER JOIN Address_Member ON Address.AddressID = Address_Member.AddressID INNER JOIN Member ON Address_Member.MemberID = Member.MemberID WHERE Member.Email = '" + Session["Email"] + "'";
            SqlCommand cmd = new SqlCommand(query, conn);

            adapter = new SqlDataAdapter(cmd);
            adapter.Fill(dt);
            adapter.Fill(dadt);
            adapter.Fill(da);



            if (dt.Rows.Count > 0)
            {
                string membercmd = "UPDATE Member SET MemberName=@MemberName,Email=@Email,Phone=@Phone";
                SqlCommand Member = new SqlCommand(membercmd, conn);

                Member.Parameters.AddWithValue("@MemberName", TxtEName.Text);
                Member.Parameters.AddWithValue("@Email", TxtEEmail.Text);
                Member.Parameters.AddWithValue("@Phone", TxtEPhone.Text);
                Member.ExecuteNonQuery();

            }

            if (da.Rows.Count > 0)
            {
                string Addresscmd = "UPDATE Address SET HouseNumber ='" + TxtEHouse.Text + "', AddressLine1 = '" + TxtEA1.Text + "', AddressLine2 = '" + TxtEA2.Text + "', City = '" + TxtECity.Text + "',PostCode = '" + TxtEPostcode.Text + "', AddressType = '" + TxtEType.Text + "'";
                SqlCommand Address = new SqlCommand(Addresscmd, conn);
                Address.ExecuteNonQuery();

            }
            else
            {

                string AddressInsert = "INSERT INTO Address (HouseNumber, AddressLine1, AddressLine2, City, Postcode, AddressType) VALUES (@HouseNumber, @AddressLine1, @AddressLine2, @City, @Postcode, @AddressType)";
                SqlCommand Address1 = new SqlCommand(AddressInsert, conn);
                Address1.Parameters.AddWithValue("@HouseNumber", TxtEHouse.Text);
                Address1.Parameters.AddWithValue("@AddressLine1", TxtEA1.Text);
                Address1.Parameters.AddWithValue("@AddressLine2", TxtEA2.Text);
                Address1.Parameters.AddWithValue("@City", TxtECity.Text);
                Address1.Parameters.AddWithValue("@Postcode", TxtEPostcode.Text);
                Address1.Parameters.AddWithValue("@AddressType", TxtEType.Text);
                Address1.ExecuteNonQuery();

                string AddressMember = "INSERT INTO Address_Member (AddressID,MemberID) VALUES (@AddressID,@MemberID)";
                SqlCommand Address_Member = new SqlCommand(AddressMember, conn);
                Address_Member.ExecuteNonQuery();
            }


                conn.Close();
                Response.Write("<script>alert('Changes saved')</script>");
                Response.Redirect("~/MyAccount.aspx");


        }



        catch (Exception ex)
        {
            Response.Write("<script>alert('Changes not saved')</script>" + ex);
            conn.Close();
        }

    }
}
Posted
Updated 27-Apr-18 18:22pm
v4

Not a solution to your question, but another problem you have.
C#
string Addresscmd = "UPDATE Address SET HouseNumber ='" + TxtEHouse.Text + "', AddressLine1 = '" + TxtEA1.Text + "', AddressLine2 = '" + TxtEA2.Text + "', City = '" + TxtECity.Text + "',PostCode = '" + TxtEPostcode.Text + "', AddressType = '" + TxtEType.Text + "'";

Why are you using code subject to SQL injection in the UPDATE when the INSERT is protected against ?

Never build an SQL query by concatenating strings. Sooner or later, you will do it with user inputs, and this opens door to a vulnerability named "SQL injection", it is dangerous for your database and error prone.
A single quote in a name and your program crash. If a user input a name like "Brian O'Conner" can crash your app, it is an SQL injection vulnerability, and the crash is the least of the problems, a malicious user input and it is promoted to SQL commands with all credentials.
SQL injection - Wikipedia[^]
SQL Injection[^]
SQL Injection Attacks by Example[^]
PHP: SQL Injection - Manual[^]
SQL Injection Prevention Cheat Sheet - OWASP[^]
   
Some observations
- As already pointed out, use parameters, always. In some parts you already use them so you know how they work. Just use them everywhere.
- Use using blocks to properly dispose the objects when not needed anymore
- To get the newly inserted key after inserting into Address table, you can use @@IDENTITY (Transact-SQL) | Microsoft Docs[^]
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900