-1

In my program, I want to fetch the data from the database from different tables and compare them with each other but it only shows registered as the strings are not equal.

<?php
$id = $_SESSION["teacher_id"];
$sql1 = "SELECT sem FROM students_data where mentor='$id'";
$sql2 = "SELECT sem FROM teacher where teacher_id='$id'";
($result1 = mysqli_query($db, $sql1)) or die(mysqli_error());
($result2 = mysqli_query($db, $sql2)) or die(mysqli_error());

if ($result1 == $result2) {
    echo "Registered";
} else {
    echo "Not Registered";
}
?>
Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
  • You question not so clear, please provide [mre] – Slava Rozhnev Jun 05 '21 at 10:02
  • 1
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Jun 05 '21 at 10:11
  • You have an error. [`mysqli_error()`](https://www.php.net/manual/en/mysqli.error.php) needs one argument. Please consider switching error mode on instead. [How to get the error message in MySQLi?](https://stackoverflow.com/a/22662582/1839439) – Dharman Jun 05 '21 at 10:11

1 Answers1

0

You can compare both tables using a single query. This query will select all the entries from students_data, and if the name is different than the name in teacher, is_different will be 1, otherwise it's 0:

SELECT
    students_data.sem,
    IF(students_data.sem != teacher.sem, 1, 0) AS is_different
FROM
    students_data
LEFT JOIN
    teacher
ON
    teacher.teacher_id = students_data.mentor

Then you can get the query result and use it in your if statement:

$arr = mysqli_fetch_assoc($result)
if ($arr['is_different'] == 1) {
    echo "Registered"; } 
else { 
    echo "Not Registered";
     }

Dharman
  • 30,962
  • 25
  • 85
  • 135
NeoSoul
  • 122
  • 1
  • 8