How can you compare values from two tables in a MySQL database using PHP?
To compare values from two tables in a MySQL database using PHP, you can use a SQL query that joins the two tables based on a common column and then retrieve the desired values for comparison. You can then loop through the results and compare the values as needed.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to compare values from two tables
$sql = "SELECT table1.column1, table2.column2 FROM table1 JOIN table2 ON table1.common_column = table2.common_column";
$result = $conn->query($sql);
// Compare values
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row['column1'] == $row['column2']) {
echo "Values match: " . $row['column1'] . " = " . $row['column2'] . "<br>";
} else {
echo "Values do not match: " . $row['column1'] . " != " . $row['column2'] . "<br>";
}
}
} else {
echo "No results found.";
}
// Close connection
$conn->close();
?>