简体   繁体   中英

Inserting values into table from textboxes & from another table's foreign key C#

Im trying to insert into a table values from textboxes AND to retrieve a foreign key id from another table and insert that also.

So I have a users table which contains UserId and I want this inserted into a nutrition diary which includes all the data that comes from textboxes(ie Weight, Height, Date etc)

I am retrieving the MemberId by using a session to track the username(lblRegistered) Here is my code:

SqlConnection con = new SqlConnection("path for my connection");
con.Open();

SqlCommand cmd = new SqlCommand("select COUNT(*)FROM Members where Username='" + lblRegistered.Text + "'", con);

con.Close();

con.Open();

cmd.CommandText = "INSERT INTO Nutrition(Weight, Height, Bmi, Date, WaterIntake, CalorieIntake, MemberId) values ('" + txtWeight.Text + "','" + txtHeight.Text + "','" + txtBmi.Text + "','" + txtDate.Text + "','" + txtWater.Text + "','" + txtCalorie.Text + "', Select Users.UserId From Users where (Users.Username= '" + lblRegistered.Text + "'))";

cmd.ExecuteNonQuery();
cmd.Clone();
con.Close();
Response.Redirect("Success.aspx");

The error is close to Select Users part.

Any help would be greatly appreciated!

First thing would be to read up on parameterized SQL queries. The code you have there is completely open to SQL injection attacks.

This is a good resource for that: http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html

Then for the problem you would be better off using a Stored Procedure to do the work. Something along the lines of :

CREATE PROCEDURE Nutrition_Insert
    @weight varchar(10),
    @height varchar(10),
    @bmi varchar(10),
    @date varchar(10),
    @username varchar(10),
    //etc for your fields
AS BEGIN

    DECLARE @memberId varchar(10)
    SELECT @memberId = UserId From Users where Username = @username

    INSERT INTO Nutrition(Weight, Height, Bmi, Date, WaterIntake, CalorieIntake, MemberId) 
    values (@weight, @height, @bmi, ....., @memberId)

END

Note - I've made some assumptions there as I don't know your data types, they all look like strings, but not knowing the size of the varchar used, I picked an arbitary value. Replace the (10) with the actual field size.

If you must use embedded SQL - then this is how you parameterize it. I've also fixed the insert statement to pull the MemberId from the Members table as part of the insert.

        using (var conn = new SqlConnection("YOUR CONNECTION STRING"))
        {
            conn.Open();
            using (
                var cmd = new SqlCommand(
                    "INSERT INTO Nutrition(...fields...) SELECT @Weight, @Height, @Bmi,...., Members.MemberId FROM Members WHERE Members.Username = @Username", conn)
                )
            {

                cmd.Parameters.AddWithValue("@Weight", txtWeight.Text);
                cmd.Parameters.AddWithValue("@Height", txtHeight.Text);
                ...
                cmd.Parameters.AddWithValue("@Username", lblRegistered.Text);

                cmd.ExecuteNonQuery();
            }
            conn.Close();
        }

You'll notice the using statements too. This will make sure your connection are disposed of cleanly.

Hope that helps.

Thanks Richard..that worked very well on the problem. I am just trying to do the same technique on a different page but this time it will have 2 where clauses

  var cmd = new SqlCommand("INSERT INTO AssignPlan(Reps, Sets, WeightOrTime, Date, MemberId, ExerciseId) Select @Reps, @Sets,@WeightOrTime,@Date, Members.MemberId From Members Where Members.Username=@name,ExerciseDisplay.ExerciseId From ExerciseDisplay Where ExerciseDisplay.ExerciseName=@Exercise", conn)

It's showing up an error from the syntax. Can this be achieved?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM