Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare two arrays of data retrieve from database?

Tags:

sql

php

mysqli

I have two arrays. In one array, I store data from one table. I store data from another table in the other array. I wanted to compare data from both of the arrays. If the data of the first array is in the second array, I want to proceed. How can I perform this?

I tried the following code but it's not working event though the array1 number exists in array2:

$x = "SELECT * FROM table1";
$data1 = mysqli_query($link, $x);
$dat1 = array()
while($row1= mysqli_fetch_array($data,MYSQLI_ASSOC))
{
  $dat1[] = $row1;
  $f1 = $row1['fid'];
}

$y = "SELECT * FROM table2";
$data2 = mysqli_query($link, $y);
$dat2 = array()
while($row2= mysqli_fetch_array($data2,MYSQLI_ASSOC))
{
  $dat2[] = $row2;
  $f2 = $row2['fid'];
}

if(in_array($dat1,$dat2))
{
  // if exists proceed
}
else
{
  // if not show error
}
like image 839
user3801544 Avatar asked Dec 05 '25 16:12

user3801544


1 Answers

This can be done by SQL.

To check if all fids in table1 are in table2:

SELECT COUNT(a.fid) FROM table1 AS a WHERE a.fid IN (SELECT b.fid FROM table2 AS b)

SELECT COUNT(*) FROM table1

If the two values are equal, then all fids in table1 are in table2.

like image 179
sotirojo Avatar answered Dec 08 '25 08:12

sotirojo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!