1

As the title says, I need help for my website. I need to copy a certain data from a table and put it on the other table. I tried to use the all kinds of languages / procedures but it still doesn't work.

Here's my code:

[HttpPost, ActionName("AddSubjects")]
[ValidateAntiForgeryToken]
public ActionResult AddSubjectConfirm(string s)
{
    DataTable dr = new DataTable();

    SqlDataAdapter dat = new SqlDataAdapter();
    SqlConnection con = new SqlConnection(@"data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=|DataDirectory|\UESLDB.mdf;");
    string qu = "INSERT INTO EnrolledSubjects (SubjectCode, SubjectDescription) SELECT SubjectCode, SubjectDescription FROM Subjects WHERE SubjectCode = '" + s + "'";

    con.Open();

    SqlCommand cmd = new SqlCommand(qu, con);
    cmd.Connection.Open();
    cmd.ExecuteNonQuery();
    con.Close();

    return View("Home");
}

A student needs to add a subject (which is already on the database for subjects) then the subject code of the subject will be stored in the "string s" and the controller will find the subject with similar subject code and then it will get the subjectcode and description and insert it to another table.

The thing is I don't know what's wrong. If somebody can help me I will be truly grateful.

Sorry for my bad explanation I'm a newbie.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    first try to do this in Sql Server management studio and see if it works. – Steve Sep 17 '18 at 20:02
  • Also, you should look into [parameterized sql queries](https://stackoverflow.com/a/7505842/4416750). – Lews Therin Sep 17 '18 at 20:25
  • At least, to avoid SQL Injection, change this line for : `string qu = "INSERT INTO EnrolledSubjects (SubjectCode, SubjectDescription) SELECT SubjectCode, SubjectDescription FROM Subjects WHERE SubjectCode = '" + s.Replace("'", "''") + "'";` – DanB Sep 17 '18 at 20:37
  • thank you for your response. I only have a little knowledge about database. Is the parameterized sql queries the best solution for my problem or is there another way like using linq or entity framework? – Jerome Agda Sep 18 '18 at 07:51

0 Answers0