Eugene Eugene - 3 months ago 31
SQL Question

Search database UWP

I have UWP app and need to search for mobile number in my database.

Now I make search like this:

searchButton.Click += delegate

{

telephone = searchtext.Text;

using (MySqlConnection connection = new MySqlConnection("Database= ******;Data Source=**********;User Id=**********;Password=********; SslMode=None; CharSet=utf8"))
{

connection.Open();


MySqlCommand createCommand = new MySqlCommand("SELECT * FROM reg_user WHERE mob LIKE N'%+380675090373%'", connection);
EncodingProvider ppp;
ppp = CodePagesEncodingProvider.Instance;
System.Text.Encoding.RegisterProvider(ppp);
MySqlDataReader reader = createCommand.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Debug.WriteLine("{0}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}\t{10}\t{11}\t{12}", reader.GetString(0), reader.GetString(1)
, reader.GetString(2), reader.GetString(3),reader.GetString(4), reader.GetString(5), reader.GetString(6),reader.GetString(7), reader.GetString(8), reader.GetString(9),reader.GetString(10), reader.GetString(11), reader.GetString(12));


}
}
else
{
Debug.WriteLine("No rows found.");
}
reader.Close();

//Debug.WriteLine(reader.ToString());
}
};


I need to take string from
textbox
and search for string that I take from it.

I made taking string like this
telephone = searchtext.Text;
Where I need to paste
telephone
variable?

I know that is simple question, but I need help.

Thank's

Answer

Quick and dirty version : replace the phone number in your SQL statement by your telephone variable.

MySqlCommand createCommand = new MySqlCommand("SELECT * FROM reg_user WHERE mob LIKE N'%" + telephone + "%'", connection);

This is not safe if you don't check user input ! You are creating an opening for SQL injection...

For a safer version, you should use parameters. Below is an example, inspired from this documentation :

string sql = @"SELECT * FROM reg_user WHERE mob LIKE N'%' + @telephone + '%'";
MySqlCommand cmd = new MySqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@telephone", "+3333333333");