大家下午好:)
我想在 PHP 页面上将 MySQL 输出显示为行而不是列,以便于移动查看和滚动(这样用户只需向下滚动数据而不是横向滚动)。
我读过有关数据透视和转置的内容,但不确定转换网页上的返回数据输出的最合适方法是什么。请问您能建议最好使用什么吗?看起来用 PHP 比用 MySQL 更容易?
我正在使用标准的帖子表单、连接 PDO、isset、thead、php echo td 和 th 等。
我当前的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title></title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<h1>Find people</h1>
<form method="post">
<label for="people">Enter person</label>
<input type="text" id="people" name="people">
<input type="submit" name="submit" value="View Results">
</form>
<?php
//error_reporting(-1);
//ini_set('display_errors', 'On');
if (isset($_POST['submit'])) {
try {
require "./config.php";
require "./common.php";
$connection = new PDO($dsn, $username, $password, $options);
$sql = "SELECT *
FROM Basics
WHERE UniqueID = :people";
$people = $_POST['people'];
$statement = $connection->prepare($sql);
$statement->bindParam(':people', $people, PDO::PARAM_STR);
$statement->execute();
$result = $statement->fetchAll();
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
?>
<?php
if (isset($_POST['submit'])) {
if ($result && $statement->rowCount() > 0) { ?>
<h2>Results</h2>
<table>
<?php echo '<table border="1">';?>
<thead>
<tr>
<th>Field 1</th>
<th>Field 2</th>
<th>Field 3</th>
</tr>
</thead>
<tbody>
<?php foreach ($result as $row) { ?>
<tr>
<td><?php echo escape($row["Field 1"]); ?></td>
<td><?php echo escape($row["Field 2"]); ?></td>
<td><?php echo escape($row["Field 3"]); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } else { ?>
<br>No results found for <?php echo escape($_POST['people']); ?>, as the data has likely not been added yet.
<?php }
} ?>
<!--
<?php if (isset($_POST['submit']) && $statement) { ?>
<?php echo escape($_POST['people']); ?> successfully found.
<?php } ?>
-->
</body>
</html>
我当前的输出:
当前示例输出:
我想要的输出示例:
与我发现的这个例子类似(可以在表格中,也可以不像下面那样):
更新编辑:
看起来我只需要使用 ul 和 li!
<ul>
<li><b>Name:</b> <?php echo escape($row["Name"]); ?></li>
</ul>
最佳答案
我将使用 array_walk() 遍历行,并在该循环内,启动 tr 标签,遍历当前行的值,将它们输出为 td 元素,退出 td 循环,输出结束tr-tag 并退出 tr-loop。不是那么奇特的解决方案,但很简单。
关于php - 在 PHP 中将 MySQL 输出显示为行而不是列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56446442/