From the code, I want these 2 tables (personal and information) to compare whether it has the same location or not. If there is a matched, I want to display the data from personal table as stated at the comment.
$selectall = "SELECT * FROM information";
$stmt = mysqli_query($connection, $selectall);
$compare = "SELECT * FROM personal INNER JOIN information ON personal.location = information.location";
$comparing = mysqli_query($connection, $compare);
while($row = mysqli_fetch_array($stmt)) {
$output .= '<tr>
<td>' .$row['name']. '</td>
<td>' .$row['location']. '</td>
<td>' .$row['postal']. '</td>
</tr>
<tr>
<td>//This is where I want to show the matched data from personal table</td>
</tr>';
}
I think what you needed is the results from $comparing
query and not the $selectall
.
If you want specific columns to be returned, the SQL can be manipulated toi return only the columns needed. e.g:
SELECT column_from_information, other_column_you_want, personal.location FROM personal INNER JOIN information ON personal.location = information.location
The idea is you can define columns with prepended table names i.e. personal.name, information.location, etc.
while($row = mysqli_fetch_array($comparing)) {
$output .= '<tr>
<td>' .$row['name']. '</td>
<td>' .$row['location']. '</td>
<td>' .$row['postal']. '</td>
</tr>
<tr>
<td><!--Matched Data--></td>
</tr>';
}
If you want to get everything in information
, even if it doesn't have a match in personal
, use an outer join. For rows that don't have a match, the columns from personal
will contain null
.
You should select the columns you want explicitly. If you use SELECT *
and there are columns with the same name in both tables, $row['columnname']
gets the value from the second table, which will be null
when there's no match. Since you want the value from the first table, select it specifically.
$compare = "SELECT i.name, i.location, i.postal, p.somecolumn, p.anothercolumn FROM information AS i
LEFT JOIN personal AS p
ON p.location = i.location";
$comparing = mysqli_query($compare);
while ($row = mysqli_fetch_assoc($comparing)) {
$output .= '<tr>
<td>' .$row['name']. '</td>
<td>' .$row['location']. '</td>
<td>' .$row['postal']. '</td>
</tr>
<tr>
<td>' . $row['somecolumn'] . '</td>
<td>' . $row['anothercolumn'] . '</td>
</tr>';
}