Saracoglu Saracoglu - 1 year ago 74
MySQL Question

Compare the two data - MySQL & PHP

I want to compare the two data and if the data are identical with each other, write the name of the data

How can a better query?

For Example:

ExampleTable1 * ID = 5 --
| (5=5) ---> "Hello This Five" (vtname)
ExampleTable2 * BEID = 5 --


SQL:

$sql1 = "SELECT * FROM ExampleTable1 WHERE paid= ".$paidsi;
$result1 = mysqli_query($conn, $sql1);
if (mysqli_num_rows($result1) > 0) {
while($row1 = mysqli_fetch_assoc($result1)) {
$sql2 = "SELECT * FROM ExampleTable2";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
if ($row2["id"] == $row1["beid"]) {
echo $row2["vtname"];
} else {
echo "";
}
}
} else {
echo "0 results";
}
}
} else {
echo "0 results";
}

Answer Source

use left join

$sql1 = "SELECT * FROM ExampleTable1 E1
            LEFT JOIN ExampleTable2 E2 ON E1.id = E2.beid";

$result1 = mysqli_query($conn, $sql1); 

if (mysqli_num_rows($result1) > 0) { 
    while($row1 = mysqli_fetch_assoc($result1)) {
        echo $row1['vtname']; 
    }
}

With this query you will only get the data you actually want, so less data moved between database server and script, and less code to manipulate it

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download