0

I have a form which use two tables to insert the data.

Some column in the form would be like:

scholarship name, course, year

Two tables that are involved are:

scholarshipDetail , scholarshipCourse.
  • scholarshipDetail table has scholarshipName and year
  • scholarshipCourse table has scholarshipID, course

scholarshipDetail:

schid      schName     year
-----------------------------
1          star         2015
2          moon         2016

scholarshipCourse:

schID    course
------------------
1        maths
1        english
2        maths

Assuming that the new user wants to add new scholarship which means the id will 3 and it insert into two tables. How do I that? (MANAGED TO INSERT ALR)

NEW ERROR: EDITED

public DataTable test(string name, string course)
{
    string insertsql = "INSERT INTO Table1(schName) OUTPUT INSERTED.addID  values (@schName)";

    SqlCommand cmd = new SqlCommand(insertsql,conn);

    cmd.Parameters.AddWithValue("@schName", name);

    conn.Open();
    int i = cmd.ExecuteNonQuery();

    var table1Id = (int)cmd.ExecuteScalar();

    string insertsql1 = "INSERT INTO Table2(ScholarshipID, DiplomaCourse) VALUES (@id, @course)";

    SqlCommand cmd2 = new SqlCommand(insertsql1, conn);
    cmd2.Parameters.AddWithValue("@id", table1Id);
    cmd2.Parameters.AddWithValue("@course", course);

    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = cmd;

    da.SelectCommand = cmd2;
    DataTable dt = new DataTable();
    da.Fill(dt);

    return dt;
}

The output in my table is

Table1

schID     schname
-------------------
1            jj
2            jj

Table2

TableID     schID       Course
------------------------------
1            2          Maths

the data is being inserted twice in Table1. why is that so? (SOLVED)

Edited:

Now the problem is, there will be checkboxes which allow the user to choose which course is applicable for the scholarship.

When the user click all checkbox, only the last checkbox will insert into database.

In my codebehind(cs):

protected void Button1_Click(object sender, EventArgs e)
{
      //  addScholarship[] test = new addScholarship[1];

        string course = "";
        string Name = schName.Text;

        if (DIT.Checked )
        {
            course = "DIT";
        }

        if (DFI.Checked)
        {
            course = "DFI";
        }

        addScholarship[] insertName = new addScholarship[1];
        addScholarship insertedName = new addScholarship(Name,course);

        scholarshipBLL obj = new scholarshipBLL();
        DataTable dt = obj.test(Name, course);
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
skylight
  • 69
  • 10
  • *assuming that the new user wants to add new scholarship which means the id will 3 and it insert into two table* -- does your `scholarshipDetail` table have `auto_increment` property? if so, your insert will always give `+1` for new row entry's id. that way, you might want to retrieve that id using [mysqli_insert_id](https://dev.mysql.com/doc/apis-php/en/apis-php-mysqli.insert-id.html), [an example](http://www.w3schools.com/php/php_mysql_insert_lastid.asp).. but, what if two people actually use the system -- that answer belongs to database transaction.. – Bagus Tesa Jan 20 '17 at 02:17
  • yes it does have auto increment. so the schID is actually an auto increment each time new scholarship is added. question is how to i get that new id inserted in my scholarshipCourse table. As for now i am able to insert into two table. but my schID in scholarshipCourse is NULL – skylight Jan 20 '17 at 02:22
  • And i am using asp.net fyi :) – skylight Jan 20 '17 at 02:22
  • ah sorry @skylight, well.. i think you better off with Entity Framework instead of plain queries for easier, although [there is an example to retrieve last id](http://stackoverflow.com/questions/5228780/how-to-get-last-inserted-id), but never tried myself. – Bagus Tesa Jan 20 '17 at 02:55
  • How are you passing the selected checkbox values from UI to the code behind? What is your logic to use all the selected checkbox value? – Chetan Jan 20 '17 at 05:34
  • i have edited the code. u can see it above. @ChetanRanpariya – skylight Jan 20 '17 at 05:38
  • I have posted answer below. Going forward please create a new question for any other issue you are facing. Updating the same question with different issue is not recommended. Also please mark the answers useful if they have helped you to resolve your issue. – Chetan Jan 20 '17 at 05:56
  • @skylight Both the issues which you reported were due to the logic issue in the code. Hence please try to debug the code and understand the logic and cause of the behavior and resolve it before looking for an answer online. This would save a lot of time of yours and others. – Chetan Jan 20 '17 at 05:58

3 Answers3

0
BEGIN;

  INSERT INTO scholarshipDetail(schid,schName,year)  VALUES(3,'sun',2017);

  INSERT INTO scholarshipCourse(schID,course) VALUES(LAST_INSERT_ID(),'science');

COMMIT;
Meer
  • 2,765
  • 2
  • 19
  • 28
  • make sure schid in scholarshipDetail is auto_increment – Sarawanakumar Jan 20 '17 at 02:27
  • Hi please take a look at the question above. i have edited and it manages to inserted the last id. However, in my databse it inserted twice. eg will be explained above @sarawanakumar – skylight Jan 20 '17 at 03:13
  • there's nothing wrong in your code, i assume public DataTable test run 2 times , try debugging – Sarawanakumar Jan 20 '17 at 03:25
  • Although this code might solve the problem, one should always consider adding an explanation to it. – BDL Jan 20 '17 at 13:55
0

You are executing the command twice.

int i = cmd.ExecuteNonQuery();

var table1Id = (int)cmd.ExecuteScalar();

You need to execute only one. I think removing cmd.ExecuteNoteQuery would solve your issue.

Chetan
  • 6,711
  • 3
  • 22
  • 32
0

For the latest problem you posted. You are calling obj.test method only once after all the if blocks.

So the "course" variable will have value from the latest if block where the condition is true.

You need to call DataTable dt = obj.test(Name, course); method in every if block. That means if checkbox is checked you call insert row. If not checked then you don't insert the row. Following is the code you should put in your button_click.

string course = "";
string Name = schName.Text;
scholarshipBLL obj = new scholarshipBLL();

List<addScholarship> addScholarshipList= new List<addScholarship>();

addScholarship scholarship;
if (DIT.Checked )
{
    scholarship = new addScholarship(Name,course);
    addScholarshipList.Add(insertedName);
    course = "DIT";
    DataTable dt = obj.test(Name, course);

}

if (DFI.Checked)
{
    scholarship = new addScholarship(Name,course);
    addScholarshipList.Add(insertedName);
    course = "DFI";
    DataTable dt = obj.test(Name, course);

}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Chetan
  • 6,711
  • 3
  • 22
  • 32
  • Hi thank you for your help. right now in my database, it gives me empty. not null and no value. what could be the reason? @ChetanRanpariya – skylight Jan 20 '17 at 06:23
  • based on your answer: there are two insertName. i believe for addScholarship insertName should be insertedName? – skylight Jan 20 '17 at 06:24
  • Apologies.. there was a slight problem in the code. But it was quite clear from the code that course variable was assigned actual value after calling obj.Test method that's why it was going blank in your database. Not sure how you could not pick this up. – Chetan Jan 20 '17 at 06:30
  • About the variable name issue. I corrected the code with meaningful names of the variables. Re-iteraing : Both the issues which you reported were due to the logic issue in the code. Hence please try to debug the code and understand the logic and cause of the behavior and resolve it before looking for an answer online. This would save a lot of time of yours and others. – Chetan Jan 20 '17 at 06:34
  • Yes i get it why it is inserted empty because i have declared variable. Now it has successfully added in accordingly to the checkbox. But i have facing another problem. when i clicked on two checkboxes, i still couldnot get both course to be inserted in my db. @ChetanRanpariya – skylight Jan 20 '17 at 06:42
  • If user clicked two checkboxes, which course is not inserting in the db? First one or second one? How do you find out that it is inserting only one course? Are you using the approach which I suggested? Did you try to debug and see if insert query is executed for both the courses? Is it executing both the if blocks? How many rows are being inserted in Table1 ? – Chetan Jan 20 '17 at 06:48
  • http://stackoverflow.com/questions/41757865/insert-two-data-in-different-row-with-same-id-in-another-data olease go to this link for new problem. Thanks @ChetanRanpariya – skylight Jan 20 '17 at 07:04