简体   繁体   English

mysql查询以在重复列中显示结果

[英]mysql query to display results in repeating columns

I am trying to build a comparison table using mysql query and php. 我正在尝试使用mysql查询和php建立一个比较表。

I would like the result to be displayed in a columns, like this: 我希望将结果显示在这样的列中:

<table border="1" cellspacing="0" cellpadding="0">
  <tr>
    <td width="151" scope="col">product</td>
    <td width="89" scope="col">product1</td>
    <td width="78" scope="col">product2</td>
    <td width="77" scope="col">product3</td>
  </tr>
  <tr>
    <td>type</td>
    <td>type2</td>
    <td>type3</td>
    <td>type5</td>
  </tr>
  <tr>
    <td>size</td>
    <td>size2</td>
    <td>size1</td>
    <td>size4</td>
  </tr>
  <tr>
    <td>price</td>
    <td>4.99</td>
    <td>3.99</td>
    <td>3.59</td>
  </tr>
</table>

but I can only get the table to show the results - not a row title too (ie I want the first column to show 'product', 'type', 'size', 'price'. 但是我只能使表格显示结果-也不能显示行标题(即,我希望第一列显示“产品”,“类型”,“尺寸”,“价格”。

The code I have so far is 我到目前为止的代码是

    <?php
// query the database
$result = mysql_query($query_getproducts);

// cols we are interested in (from the SQL query)
$cols = array(
        'product',
    'type',
    'size',
    'price',
  );

// 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 border=1 width=473>";
echo "<tr>";

echo "</tr>";
foreach($rotated as $col => $values) {
  echo "<tr>";

  foreach($values as $value) {
    echo "<td> " . htmlentities($value) . "</td>";
  }
  echo "</tr>";
}
echo "</table>";
?>

hope someone can help. 希望有人可以帮忙。

First of all mysql_* functions are deprecated. 首先,不建议使用mysql_ *函数。 You should use PDO or Mysqli. 您应该使用PDO或Mysqli。

If you want table headers static ie you want to show table header as "Product,Type,Size, Price" Then use 如果您希望表格标题是静态的,即要将表格标题显示为“ Product,Type,Size,Price”,则使用

<tr>
<th>Product</th>
<th>Type</th>
<th>Size</th>
<th>Price</th>
</tr>

Then if your should use mysql_fetch_assoc which returns associative array with column name as there key. 然后,如果您应该使用mysql_fetch_assoc,它返回带有列名作为键的关联数组。 You can use that array and print the result using loop. 您可以使用该数组并使用循环打印结果。 eg: 例如:

<?php
$rs=mysql_query($query);
while($row=mysql_fetch_assoc($rs) ){
?>
<tr>
<td><?php echo $row['keyname']?></td>
.....
.....
</tr>
<?php
}
?>

try like this , 这样尝试,

echo "<table border=1 width=473>";
echo "      <tr>
    <th>Product Name</th>
    <th>Description</th>
    <th>Product Size</th>
    <th>Price</th>
    </tr>";
foreach($rotated as $col => $values) {
 echo "<tr>";

 foreach($values as $value) {
    echo "<td> " . htmlentities($value) . "</td>";
  }
  echo "</tr>";
}
echo "</table>";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM