doulan2827 2016-12-18 13:03
浏览 35
已采纳

将两个查询中的值匹配到同一个表中

I'm trying to add a description to a coded value on PHP. The code was extracted from a table, and the description from another. The idea is that they are presented on a table with the proper description for each code, but when I tried to add the raw ordered query, the descriptions where misplaced, so I tried this:

 <table>
 for($i=0; $i < $items; $i++)
 {
     $row = $results -> fetch_array();
     echo '<tr>';
     echo '<td>'.$row['code'].'</td>';
     for($j=0; $j<$items2; $j++) 
     {
         $row2 = $result2 -> fetch_array();
         if ($row['code'] == $row2['code']) 
         {
             echo '<td>'.$row2['description'].'</td>';
         }
     }
     echo '</tr>';
 }
 echo '</table>';

It's working for the first value, but only that one, the rest of the column is empty.

  • 写回答

2条回答 默认 最新

  • doupiai5597 2016-12-18 13:29
    关注

    I think your problem is, that you have to reset the row pointer for $result2.

     <table>
     for($i=0; $i < $items; $i++)
     {
         $row = $results -> fetch_array();
         echo '<tr>';
         echo '<td>'.$row['code'].'</td>';
         for($j=0; $j<items2; $j++) 
         {
             $result2 -> data_seek( 0 );
             $row2 = $result2 -> fetch_array();
             if ($row['code'] == $row2['code']) 
             {
                 echo '<td>'.$row2['code'].'</td>';
             }
         }
         echo '</tr>';
     }
     echo '</table>';
    

    Every time you call fetch_array, an internal row pointer is incremented by one. So in the outer for loop´s second cycle, $result2 -> fetch_array() will retun NULL since there is no more result left.

    Alternatively, you can iterate through $result2 before the first loop und store the results in a two dimensional array. However: I would prefer to use a JOIN to put together the two statements, so that you only will get one resultset. But there´s too few information provided, to see if that´s possible in this case.

    MySQL JOIN Syntax

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号