Click here to Skip to main content
15,891,748 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
C#
There are 2 comboboxes and 2 textboxes in my wpf project.
I want to set fill in validation.
It says "Fill in properly" even I fill them properly.
Below is my code:
        private void Reg()
        {
            if (txtDate.Text != null & txtTime.Text != null & cmbGroup1.SelectedIndex > 0 & cmbName1.SelectedIndex > 0)
            {
                MySqlConnection con = new MySqlConnection(constr);
                MySqlCommand cmd = new MySqlCommand("INSERT INTO Regiter(Date,Time,Image_ID,Students_ID) "
                    + "VALUES ('" + txtDate.Text + "','" + txtTime.Text + "','" + getMaxRasmID() + "','" + getStudentsID() + "')", con);
                con.Open();
                int i = cmd.ExecuteNonQuery();
                if (i > 0)
                {
                    MessageBox.Show("Registered");
                }
                con.Close();
            }
            else
            {
                MessageBox.Show("Fill in properly");
            }
            
        }
Posted
Comments
Richard Deeming 20-Jan-16 9:39am    
Your code is STILL vulnerable to SQL Injection[^].

NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.
Sergey Alexandrovich Kryukov 20-Jan-16 13:33pm    
Right; this is the key. I answered in more detail and credited your comment in Solution 1.
—SA

1 solution

Your approach is wrong from the very beginning. The query composed by concatenation with strings taken from UI. Not only repeated string concatenation is inefficient (because strings are immutable; do I have to explain why it makes repeated concatenation bad?), but there is way more important issue: it opens the doors to a well-known exploit called SQL injection. Richard Deeming made it clear in his comment to the question, but you may need some explanations.

This is how it works: http://xkcd.com/327.

Are you getting the idea? The string taken from a control can be anything, including… a fragment of SQL code.

What to do? Just read about this problem and the main remedy: parametrized statements: http://en.wikipedia.org/wiki/SQL_injection.

With ADO.NET, use this: http://msdn.microsoft.com/en-us/library/ff648339.aspx.

Please see my past answers for some more detail:
EROR IN UPATE in com.ExecuteNonQuery();,
hi name is not displaying in name?.


It has nothing to do with validation; neither your code does. If you need validation, just do it before using your SQL statement. Most likely, you will need validation just as as part of the procedure you have to perform to parse the text to some typed data you need to assign to a parameter of your parameterized statement.

—SA
 
Share this answer
 
v2

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