1

有没有办法实现将查询结果显示到列中并将记录转到下一行?

这是我的 SQL 表:

------------SQL TABLE -----------

    id   |    product_name    | product_type
    0    |    Lorem           | Table   
    1    |    Ipsum           | Chair
    2    |    Dolor           | Lamp
    3    |    Sit             | Chair

这就是我想要的。

        Lorem    |  Ipsum      |    Dolor   |   Sit       |
------------------------------------------------------------
id    | 0        |  1          |    2       |   3         |
type  | Table    |    Chair    |    Lamp    |    Chair    |

期望的输出:

    <table>
  <tr>
    <td>&nbsp;</td>
    <td>Lorem</td>
    <td>Ipsum</td>
    <td>Dolor</td>
    <td>Sit</td>
  </tr>

  <tr>
    <td>id</td>
    <td>0</td>
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>

    <tr>
    <td>type</td>
    <td>Table</td>
    <td>Chair</td>
    <td>Lamp</td>
    <td>Chair</td>
  </tr>

</table>

这是我的代码,但我知道这是非常错误的。如果使用 while 和 for 循环有意义,我只是坚持如何为字段创建新行。

    echo '<table><tr>';

        $i=1;

        while($rows = mysql_fetch_array($result)){
            echo '<td><table><tr><th>'.$rows['product_name'].
            '</th></tr><tr><td>'.$rows['product_id'].
            '</td><td>'.$rows['product_type'].'</tr></table></td>';
                if($i %2 == 0) { 
        echo '</tr>
                <tr>'; }
                }    
        echo'
        </tr>
        </table>';
4

2 回答 2

0

试试这个

      echo '<table>';


    while($rows = mysql_fetch_array($result)){
        echo '<tr><th>'.$rows['product_name'].
        '</th></tr><tr><td>'.$rows['id'].
        '</td></tr><tr><td>'.$rows['product_type'].
        '</td></tr>';

            }    
    echo' </table>';
于 2012-11-26T19:03:51.917 回答
0

您需要旋转数据。你可以使用这样的东西(未经测试):

// build query
$query = "SELECT id, product_name, product_type FROM whatevertableyouhave";

// query the database
$result = mysql_query($query);

// cols we are interested in (from the SQL query)
$cols = array(
  'id',
  'product_name',
  'product_type';
);

// initialize rotated result using cols
$rotated = array();
foreach($cols as $col) {
  $rotated[$col] = array();
}

// fill rotated array
while(($row = mysql_fetch_assoc($result)) !== false) {
  foreach($cols as $col) {
    $rotated[$col][] = $row[$col];
  }
}

// echo html
echo "<table>";
echo "<tr>";
foreach($cols as $col) {
  echo "<th>{$col}</th>";
}
echo "</tr>";
foreach($rotated as $col => $values) {
  echo "<tr>";
  foreach($values as $value) {
    echo "<td>" . htmlentities($value) . "</td>";
  }
  echo "</tr>";
}
echo "</table>";
于 2012-11-26T20:28:23.917 回答