PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, April 20, 2022

[FIXED] How do I refer to my form elements' values in a query? C# MSSQL

 April 20, 2022     c#, connection, sql-server     No comments   

Issue

I'm trying to insert data from my textbox value to the database. This code works perfectly fine

SqlCommand query = new SqlCommand(@"INSERT INTO GuestTable (CustomerName, Address) VALUES ('" + textBox1.Text + "','" + textBox2.Text + "')", con);

But I only need to insert that data to a specified ID. So I figured I need to add this:

  WHERE CustomerID = '" +Convert.ToInt32(textBox3.Text)+"'

But that line gives an error only after I ran the program saying, "Error near 'WHERE' keyword.."


Solution

In short, you do not do it like that. You should never use string concatenation within an SQL query. In C#, you should be using Parameterized Queries. Then, you can use the methods C# provides to insert your variables into the query.

Here is an example taken from Using Parameterized Query to Avoid SQL Injection

string sql = "select count(UserID) from user_login where UserID=@UserID and pwd=@pwd";  
SqlCommand cmd = new SqlCommand(sql, con);  
SqlParameter[] param = new SqlParameter[2];  
param[0] = new SqlParameter("@UserID", txtUSerID.Text);  
param[1] = new SqlParameter("@pwd", txtPwd.Text);  
cmd.Parameters.Add(param[0]);  
cmd.Parameters.Add(param[1]);


Answered By - Luke
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing