我现在有一个使用 PHP 和 MySQL 的水平表
如何从这段代码制作垂直表格?
<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/