Compare values in two tables with php and Mysqli

Asked

Viewed 234 times

0

I have to compare if the numbers in table A exist in table B and if it exists it makes one instruction or another. I tried that and it didn’t work.

Note: In table B there may not be codigo table A

EXAMPLE:

TABELA A campo => (codigo): 12,13,23,44,55
TABELA B campo => (meucampo): 13,44,55


$sql_A="SELECT * FROM A"; 
$resultado_A = $conexao->query($sql_A);
while($row_A = $resultado_A->fetch_assoc()) : ?>


    $sql_B="SELECT * FROM B WHERE meucampo = ".$row_A['codigo']." "; 
    $resultado_B = $conexao->query($sql_B);

        while($row_B = $resultado_B->fetch_assoc()) :

            if($row_A['codigo'] == $row_b['meucampo'])  :
                echo"<a href='link'>foo</a>";
                else   :
                echo"<a href='link'>foo/bar</a>";

            endif;

        endwhile; 

endwhile; 
  • 2

    Make an Outer Join with ON comparing all fields, with WHERE IS NULL() two sides. It will only return what is different. (but beware, that in cases where there is more than one identical line on both sides there is no way to differentiate) - Another alternative is to make two separate SELECTS, ordered by some field, and go giving fetch Row the side that has more "late", and comparing. If they are equal, fetch on both sides. If they are different, write down the line, and advance the lesser of the two in the ordering. It’s practical and fast, and you don’t need to accumulate everything in your memory.

  • Thanks for the reply Bacco. I did so but unsuccessfully to seeing other ways. SELECT * FROM categoriassub OUTER JOIN categories ON categoriassub.category = categories.code WHERE category.code IS NULL. If it is possible to present practical example thank you. I am testing other ways.

  • 1

    In this your code is not "comparing all fields" and has no "IS NULL() on both sides"

  • 1

    I think if the query results in zero records, while won’t even run, not entering your IF code == myfield, then check with numrow > 0

  • Thank you all solved.

No answers

Browser other questions tagged

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