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

2

In a login system, I want the user to type 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 repeating code. Is there a more logical way to do this?

Something like:

WHERE usuario or email = '$user'
    
asked by anonymous 06.11.2016 / 15:25

2 answers

4

Whether a field has multiple values or whether a value is in several different values can be used to IN . Here are two examples:

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

and to search for 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"

So, in your case:

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

See working on SQL Fiddle .

IN starts to be advantageous in several parameters, for example in IN ( usuario, email, inscricao, cpf ) if one day needs it in some application. The gain in speed / processing is minimal (basically saves transmission and allocation of repeated values), but ease of maintenance and legibility increases a bit.

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

    
06.11.2016 / 15:38
2

That's the way it's done. There is no shortcut.
But I suggest delimiting between parentheses to avoid inconsistency:

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

Obviously, disregarding the use of VIEW or custom functions.

    
06.11.2016 / 15:32