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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?