Hải Phan Thanh
Hải Phan Thanh

Reputation: 33

How to compare two table SQL in PHP code?

I want to compare two SQL table( code PHP) : Class1 & Class2

   Class1                      Class2

ID   | Name  | Age           ID  | Name | Age 

101  | Bob   | 20            101 | Bobb | 22
102  | Jame  | 21            102 | Jame | 21 
103  | Kenny | 21 

Suppose, the difference is mistake while typing and Class1 is the original data.

How to hightlight difference in both ( two) table and show this in PHP site. Like that

           Class1                      Class2

ID       |    Name   | Age           ID  | Name      | Age 

101      | **Bob**   | **20**        101 | **Bobb**  | **22**
102      | Jame      | 21            102 | Jame      | 21 
**103**  | **Kenny** | **21** 

My mean is color or bold in PHP code.

Thanks for your help.

Upvotes: 0

Views: 44

Answers (1)

LSerni
LSerni

Reputation: 57388

You need to join the two tables using the ID:

SELECT a.*, b.* FROM a LEFT JOIN b USING (id)

and drop identical records

WHERE 
     (a.field1 != b.field1 OR b.field1 IS NULL)
     OR
     (a.field2 != b.field2 OR b.field2 IS NULL)

You can build the WHERE from a foreach() loop on the field names, using implode(' OR ', ...) to join the clauses for each field.

Then you present the records in a table, again with a foreach() loop inside the while($resultset->fetch()) loop, to only highlight the fields that are different.

Upvotes: 1

Related Questions