从嵌套的MySQL Select中显示

时间:2012-12-06 16:14:17

标签: php mysql select nested

我试图尽可能地清理它。为了便于阅读,我为此道歉。我肯定需要使用一个聪明的模板或类似的东西,这只是快速和肮脏。我对此非常陌生。这就是我想要完成的事情:我正在通过一个带有循环的表来运行,将所有结果返回到一个漂亮的表中。在子查询需要执行之前,它确实很好。子查询查看另一个表并使用起始循环中的$ office值来查找信息,从那里它总计整数值并将其分配给$ paid。

由于某种原因,两个循环在返回第一个结果后停止并输出$ paid。是否有可能完成我正在做的事情?我试图绕过这个问题,看起来我可以硬编码值并为每个结果集设置单独的变量,但这似乎很多工作。我只想显示从第一个循环返回的每个结果集的$ paid整数。希望这一切都有意义。我非常感谢任何建议。

$mysqli = new mysqli ( $db_hostname, $db_username, $db_password, $db_name );
    $query = "select * from `drawer` where date(`date`) = '$mysql_date' order by `office`"; // select result set for selected date and order by office name
    $result = $mysqli->query($query);
    while ( $row = $result->fetch_assoc () ) {

echo "<tr class=table_border>\n"; //display results
echo "<td class=table_rows nowrap width=10%>&nbsp;".$row['office']."</td>\n"; // return office name
$office = $row['office']; // grab the office from the first loop to use it in the second loop
echo "<td class=table_rows nowrap width=10%>&nbsp;".$row['manager']."</td>\n"; // return manager name
echo "<td class=table_rows nowrap width=10%>&nbsp;".$row['scash']."</td>\n"; // display integer value
echo "<td class=table_rows nowrap width=10%>&nbsp;".$row['ecash']."</td>\n"; // display integer value

$newquery = "select * from `offer_det` where `office` = '$office' and date(date) = curdate()"; // subquery to display data from another table and insert for each row when the first loop starts
$resultquery = $mysqli->query($newquery);
while ($row=$resultquery->fetch_assoc()) {
    $paid += $row['paid'];
}
echo "<td class=table_rows nowrap width=10%>&nbsp;".$paid."</td>\n"; // both loops end here
echo "<td class=table_rows nowrap width=10%>&nbsp;".$row['add']."</td>\n"; // should return integer value
echo "<td class=table_rows nowrap width=10%>&nbsp;".$row['remove']."</td>\n"; // should return integer
echo "<td class=table_rows nowrap width=10%>&nbsp;".$row['total']."</td>\n"; // should return integer
}

2 个答案:

答案 0 :(得分:0)

您正在将$row覆盖到内部循环

更改

while ($row=$resultquery->fetch_assoc()) {
    $paid += $row['paid'];
}

while ($row1=$resultquery->fetch_assoc()) {
    $paid += $row1['paid'];
}

答案 1 :(得分:0)

你在内部while循环中分配$ row - 它已经分配给外部循环。尝试将其更改为内循环中的其他变量名称

while ($row1=$resultquery->fetch_assoc()) {
    $paid += $row1['paid'];
}