Select multiple to avoid 2 database queries

Asked

Viewed 59 times

0

I have the following select (using PDO):

$usuariosListados = $pdo->prepare("SELECT user_1, user_2 FROM usuarios WHERE user_1 = '".$_SESSION["usuario"]."' AND estatus = 2");
$usuariosListados -> execute();
$fAll = $usuariosListados -> fetchAll(PDO::FETCH_ASSOC);
$rCount= $usuariosListados -> rowCount();


// E o seguinte foreach
if(rCount) {
    foreach($fAll as $itemUser) {
        echo "Usuário amigo: ".$itemUser["user_2"];
    }
} else {
    echo "Nenhum registro encontrado.";
}

However, I would need to make another select, but in the following way:

$usuariosListados_2 = $pdo->prepare("SELECT user_1, user_2 FROM usuarios WHERE user_2 = '".$_SESSION["usuario"]."' AND estatus = 2");

And the foreach would be:

foreach($fAll_2 as $itemUser_2) {
    echo "Usuário amigo: ".$itemUser["user_1"];
}

I wonder if there is any way to "join" these selects thus avoiding making 2 queries to the database. Remembering that, the user_1 and the user_2 will never be equal, and I need the value that corresponds to the "opposite" of the logged in user (which is the $_SESSION["usuario"]).

1 answer

2


You can make an appointment like this:

"SELECT user_1, user_2 FROM usuarios 
WHERE '" . $_SESSION['usuario'] . "' IN ( user_1, user_2 ) " .
"AND estatus = 2"

This query returns any user who is on user_1 or user_2 like the $_SESSION['usuario'].

Explanation

If you’re both wanting the user_1 where equal $_SESSION['usuario'] and also the user_2 where equal $_SESSION['usuario'], the consultation above gives just that - ie:

Consult user_1 and user_2 in the table users where $_SESSION['user'] equals at least one of the two, and also both have statues of 2.

There, your $usuariosListados->fetchAll(PDO::FETCH_ASSOC) will contain two (or more) results, being one of the user_1 and the other of user_2.

  • Can you explain it better? It got a little confusing.

  • Maybe I didn’t understand your final wish -- this consists only of giving the two users at once (just a query to the database). After that, I don’t think I understood its purpose - but I hope I was able to answer the question :|

  • (from what I understood and researched) the IN serves to return results that are equal to WHERE, but I need the different. That is, if user_1 for = a $_SESSION["usuario"] then in the foreach I will use the user_2 and vice versa. There are ways to do this?

  • I was able to adapt your answer to my problem by just doing an if/Else check, thank you very much!

  • I’m glad it worked out!

Browser other questions tagged

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