1

The question could have been different, like : Compare two tables in mySQL on a specific metric. My tables have a dimension (date) and a metric (number) and I want to check if I am getting the same number for the same date.

As a solution I started creating a PHP script where the table contents will be put into arrays. Then I am comparing this arrays to trace the differences.

If the number is not the same in the two tables for the same date , I will print the "date, number from table 1 - number from table 2".

Here is my code but it seems that I am having a problem with array_diff :

// Connect to the database (mySQL)
$Db = mysqli_init();
$Db->options(MYSQLI_OPT_LOCAL_INFILE, true);
$Db->real_connect($servername, $username, $password, $dbname, 3306);

// Creation of 1st Array
$result_one  = array();

// Creation of 1st SQL query
$sql = "select date, sum(number) from Table1 group by date";

// Run the 1st query
$query = $Db->query($sql);

// Save the results of the 1st query in the 1st array called result_one
$i = 0;
while ($row = $query->fetch_assoc()) 
{
    echo "aaa";
    $result_one[$i] = $row;
    $i++;
}

// Print the results (array)
print_r ($result_one);

#####################################################

// Creation of 2nd Array
$result_two  = array();

// Creation of 1st SQL query
$sql = "select date, sum(number) from Table2 group by date";

// Run the 1st query
$query = $Db->query($sql);

// Save the results of the 1st query in the 1st array called result_two
$i = 0;
while ($row = $query->fetch_assoc()) 
{
    echo "aaa";
    $result_two[$i] = $row;
    $i++;
}

// Print the result_two (array)
print_r ($result_two);

#####################################################

// Use of array_diff
$diff = array_diff($result_one,$result_two);

// Print the differences
print_r($diff);

I am getting an error like :

PHP Stack trace:... Array to string conversion

The tables have two dimensions

Datacrawler
  • 2,780
  • 8
  • 46
  • 100

3 Answers3

2

You can do this with a single SQL query:

$sql = "SELECT t1.date, t1.number as `t1num`, 
        t2.number as `t2num` 
        FROM `table1` t1, `table2` t2 
        WHERE t1.date = t2.date AND t1.number != t2.number"
$query = $Db->query($sql);


while ($row = $query->fetch_assoc()) 
{
    echo sprintf("mismatch: date: %s, table1: %s, table2: %s", $row['date'], $row['t1num'], $row['t2num']);
}
Steve
  • 20,703
  • 5
  • 41
  • 67
0

the function array_diff check only 1 dimensional array, and this from php manual

This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]);.

through this link

you can iterate the arrays and compare each 1 dimensional array.

this may help you

Community
  • 1
  • 1
Gouda Elalfy
  • 6,888
  • 1
  • 26
  • 38
0

array_diff function is okey, I think problem it is in $result_one and $result_two. Print them to see what there are in them.

kostova
  • 61
  • 4