简体   繁体   中英

mysql query to display results in repeating columns

I am trying to build a comparison table using mysql query and 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. You should use PDO or Mysqli.

If you want table headers static ie you want to show table header as "Product,Type,Size, Price" Then use

<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. 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>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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