I want to expand on Jimmy's answer a bit.
LASTNAME LIKE 'Pep%'
That's just EVIL. NEVER do it. The SQL string should look like this instead:
LASTNAME LIKE @LastName + '%'
Now the problem is that in your case you don't know if you need to do a lastname check at all. All you have are SELECT and FROM clauses and a textbox for the lastname column that may or may not have a value in it. Fine. That's still no excuse for doing it like in the first example. What you need to do instead is build your query like this (using C# for now since you didn't supply a client langauge):
//create a place to keep parameters until we can construct the SqlCommand object
List<SqlParameter> params = new List<SqlParameter>();
SqlParameter p;
// the StringBuilder is MUCH more efficient the concatenating strings
// the 1=1 is a placeholder so you can always just append " AND whatever"
StringBuilder sql = new StringBuilder("SELECT ... \nFROM .... \nWHERE 1=1\n");
// Check and add a parameter for the LastName column if needed
if (!String.IsNullOrEmpty(txtLastName.Text))
{
sql.AppendLine("AND LASTNAME LIKE @LastName + '%'");
p = new SqlParameter("@LastName", SqlDbType.VarChar, 50); // use the actual datatype here
p.Value = txtLastName.Text;
params.Add(p);
}
// Check and add a parameter for another field if needed
if (!String.IsNullOrEmpty(txtSomeOtherField.Text))
{
sql.AppendLine("AND OtherField LIKE @OtherParam + '%'");
p = new SqlParameter("@OtherParam", SqlDbType.VarChar, 255);
p.Value = txtSomeOtherField.Text;
params.Add(p);
}
// ... You could also write a method to abstract the code in the if blocks ...
// you haven't told us _how_ the user will specify the order, so I'm leaving that implementation detail out for now
sql.Append(" ORDER BY LastName, OtherField");
// now we can finally get our SQL String and build the (SAFE!) SqlCommand object:
SqlCommand cmd = new SqlCommand(sql.ToString(), YourSqlConnectionObjectHere);
cmd.Parameters.AddRange(params.ToArray());
Now you have a dynamically generated where clause with no possibility for injection. It works because every part of the string sent to the database is an exact literal in your code, even if those literals are assembled over a number of steps. The values used in the parameters are never substituted into the string, but instead sent to the server separately as data.
Of course this was C# (.Net), but just about every modern platform has some form of parameterized query/prepared statement feature you should be using.