PHP MySQL 垂直表

标签 php mysql html-table

我现在有一个使用 PHP 和 MySQL 的水平表

table

如何从这段代码制作垂直表格?

<div class="content-loader">
  <table cellspacing="0" width="100%" id="rank2" class="table table-striped table-hover table-responsive">
    <thead>
      <tr>
        <th>Nick</th>
        <th>Kredity</th>
        <th>Body1</th>
        <th>Body2</th>
        <th>Cas</th>
        <th>online</th>
      </tr>
    </thead>
    <tbody>
      <?php
      require_once 'dbconfig.php';
      $stmt = $db_con->prepare("SELECT ranks.steamId, ranks.points, ranks.lastDisplayName, ranks.lastUpdated, ranksrussia2.points AS points2, uconomy.balance
        FROM ranks
        INNER JOIN ranksrussia2 ON ranks.steamId = ranksrussia2.steamId
        LEFT JOIN uconomy ON ranks.steamId = uconomy.steamId
        WHERE ranks.steamId = ?");
      $stmt->execute(array($steamprofile['steamid']));

      while($row = $stmt->fetch(PDO::FETCH_ASSOC))
      {
          echo "<td>". $row['lastDisplayName']."</td><td>". $row['balance'] ."</td><td>". $row['points'] ."</td><td>". $row['points2'] ."</td><td>". $row['points2'] ."</td>";
      }
      ?>
    </tbody>
  </table>
</div>

最佳答案

当生成表格时,fetch() 逐行工作,对于水平打印的表格非常有效。但在你的情况下,最好在打印之前 fetchAll() 数据:

<?php

  function unite(string $prefix, string $suffix, array $array){
    $str = '';
    foreach($array as $value){
      $str.= $prefix . $value . $suffix;
    }

    return $str;
  }

  if($stmt->execute(array($steamprofile['steamid']))){
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  } else {
    die('query failed');
  }

?>

<table>
  <tbody>
    <tr>
      <th>Nick</th><?php echo unite('<td>', '</td>', array_column($rows, 'lastDisplayName')) ?>
    </tr>
    <tr>
      <th>Kredity</th><?php echo unite('<td>', '</td>', array_column($rows, 'balance')) ?>
    </tr>    
  </tbody>
</table>

这样您就可以抓取列并一次性打印出来。如果您不希望超过 1 列,您也可以简单地执行以下操作:

<?php

  if($stmt->execute(array($steamprofile['steamid']))){
    if(!is_array($row = $stmt->fetch(PDO::FETCH_ASSOC))){
      die('no results');
    }
  } else {
    die('query failed');
  }

?>

<tr>
  <th>Nick</th><td><?php echo $row['lastDisplayName'] ?></td>
</tr>

关于PHP MySQL 垂直表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40871599/

相关文章:

php - 根据优先级随机获取记录

php - MySQLi 多查询不起作用

mysql - 在子查询中插入多行表

php - 使用 PHP 和 MySQL 执行 SQL 查询以按关键字搜索结果时出错

PHP:查找字符串或数组中出现最频繁的单词

php - 在 PHP 中解码字符串

html 表溢出仅针对 td 隐藏

ajax 生成的 PHP 表单无法正常工作

javascript - 表行内的 KendoSparklines,其中行是动态添加的

php - DateTime 类与原生 PHP 日期函数