Reputation:
I am trying to display data from 2 different SQL Tables (normalised database) and display the data side by side in an HTML Table.
I can display the data from Table A and from Table B, however, I achieve this from two separate while-loops. I would like to combine these while-loops into one.
Question: can I have 2 mysql_fetch_array() conditions inside a while-loop?
Displaying data from Table A:
$result = mysql_query("SELECT * from ReportValues WHERE
ReportValues.ReportID = '$Report_Values'");
while ($myData = mysql_fetch_array($result, MYSQL_NUM))
{
echo "<tr>";
echo "<td>" . $myData[2] . "</td>";
echo "</tr>";
}
Displaying data from Table B:
$result = mysql_query("SELECT * FROM Element WHERE Element.ElementsID
= (SELECT ElementsID FROM Template WHERE Template.TID = '$Temp')");
while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
echo "<td>" . $row[2] . "</td>";
echo "</tr>";
}
Ideally I am trying to achieve something like this:
$result = mysql_query("SELECT * from ReportValues
WHERE ReportValues.ReportID = '$Report_Values'");
$result2 = mysql_query("SELECT * FROM Element
WHERE Element.ElementsID =
(SELECT ElementsID FROM Template
WHERE Template.TID = '$Temp'
)"
);
while ($myData = mysql_fetch_array($result, MYSQL_NUM) &&
$row = mysql_fetch_array($result2, MYSQL_NUM))
{
echo "<tr>";
echo "<td>" . $myData[2] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "</tr>";
}
Thanks in advance.
EDIT: Thank you for all the replies, however, I couldn't manage to implement what was suggested. My work around included creating arrays, and for each element (data[$i] and row[$i]) I just added them into 2 separate arrays. I still used two separate while-loops. Probably inefficient/poor code, but I got it working, ha.
Upvotes: 1
Views: 2231
Reputation: 78994
You can yes, but if there are a different number of rows returned in each query then the loop will stop when there are no more results in the one with fewer rows:
while ($myData = mysql_fetch_array($result, MYSQL_NUM) &&
$row = mysql_fetch_array($result2, MYSQL_NUM))
{
echo "<tr>";
echo "<td>" . $myData[2] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "</tr>";
}
To keep looping for the query with the most rows you could use an OR
, but you need to check if the variable is set:
while ($myData = mysql_fetch_array($result, MYSQL_NUM) ||
$row = mysql_fetch_array($result2, MYSQL_NUM))
{
echo "<tr>";
echo "<td>" . isset($myData[2]) ? $myData[2] : '' . "</td>";
echo "<td>" . isset($row[2]) ? $myData[2] : '' . "</td>";
echo "</tr>";
}
Upvotes: 1