Check if the same value is in one of the two fields

Asked

Viewed 105 times

3

In a system of login, I want the user to enter the "user" or "email" that is contained in the DB.

This works perfectly:

DBRead('usuarios', "WHERE usuario = '$user' OR email ='$user' AND senha = '$password'");

However, I hate to repeat code. There is a more logical way to perform this check?

Something like:

WHERE usuario or email = '$user'
  • 1

    That’s not exactly repeating code, you’re doing two different things. I know that some people have an obsession with writing as little code as possible, I myself have been like this, it does not lead to anything, actually enough harm. Read: http://answall.com/q/120931/101. This type of code often leads to a problem in the code. In fact, the code is well insecure, this should be your concern. You can even do what you want.

  • @Thanks for the tip! It’s not that I want to write less code, I just like working using a logic (I think it enables me to learn more about everything) xD Hug.

2 answers

4


Both to search if a field has multiple values and to search if a value is found in several different values you can use the IN. See two examples:

SELECT ... WHERE id IN (1,5,6,9); -- retorna linhas onde o ID é um, cinco, seis ou nove

and, to search a value in more than one field:

SELECT ... WHERE "xis" IN (principal, reserva, outros); -- retorna linhas em que ao menos
                                                        -- um dos três campos listados
                                                        -- seja a string "xis"

Staying so in your case:

WHERE '$user' IN ( usuario, email ) AND senha = '$password'

See working on SQL Fiddle.

The IN starts to be advantageous in several parameters, for example in IN ( usuario, email, inscricao, cpf ) if you ever need it in any application. Speed/processing gain is minimal (basically saves transmission and repeated value allocation), but ease of maintenance and readability increases a lot.


Note that you have an open port for SQL Injection if you do not sanitize the parameters, and storing passwords directly in DB is not done in real situations.

  • 1

    Perfect! Worked well. About SQL Injection: My function has an Escape.

2

That’s the way it’s done. There’s no shortcut.
But I suggest delimiting in parentheses to avoid inconsistency:

DBRead('usuarios', "WHERE (usuario = '$user' OR email ='$user') AND senha = '$password'");

Obviously disregarding the use of VIEW or custom functions.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.