【发布时间】:2019-03-02 08:11:26
【问题描述】:
我正在开发一个类似于文档管理系统的个人项目。 我正在数据库中创建与文件夹同名的新文件夹和表。
我可以列出所有这些,当我单击 HTML 表格中列出的表格名称时,我希望显示该表格中的所有内容。
但我不知道表的名称。
我得到“0 个结果”。
- 数据库表的屏幕截图 -> DB
- “O 结果”的屏幕截图 -> Results
- 列出表格的屏幕截图 -> Tables listed
但是我可以在 URL 中看到我在“正确”表中,因为它显示了我的表的名称。
我知道问题出在 view.php 中的 SELECT 语句中,我不知道如何选择我不知道名称的表:-)
有人可以帮帮我吗?
非常感谢。
这是我的索引代码,其中我将数据库中的所有表列为按钮:
<div class="container-fluid">
<div class="row">
<div class="col-md-4 col-xl-4 text-center ml-sm-2 ml-md-5 ml-lg-5 mt-5">
<div class="alert alert-danger mb-0"><strong>TABLES from DATABASE:</strong></div>
<table class="table table-bordered table-hover text-center">
<tr class="title">
<th>Folder Name:</th>
</tr>
<?php
$conn = mysqli_connect("localhost", "root", "", "folder");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT table_name FROM information_schema.tables where table_schema='folder';";
$result = $conn-> query($sql);
if ($result) {
while ($row = $result-> fetch_assoc()) {
echo "<a href='view.php?". $row['table_name'] ."' ><span style='font-size: 19px; color: #3277b6; margin-right: 15px;'><i class='far fa-eye'></i></span></a>";
}
}
else {
echo "0 results";
}
$conn-> close();
?>
</table>
</div>
这是 view.php 代码:
<body>
<div class="container">
<div class="row mt-5 ml-5">
<div class="col-md-8 col-xl-11 text-center ml-sm-2 ml-md-5 ml-lg-5 mt-5">
<div class="alert alert-danger mb-0">
<a href="index.php" class="btn btn-dark mr-5" role="button">Go Back</a>
</div>
<div style="overflow-x:auto;">
<table class="table table-bordered table-hover text-center">
<tr>
<th>Name:</th>
<th>Create at:</th>
</tr>
<?php
$conn = mysqli_connect("localhost", "root", "", "folder");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM information_schema.tables where table_name = ?";
$result = $conn-> query($sql);
if ($result) {
while ($row = $result-> fetch_assoc()) {
echo "<tr>
<td>".$row['name']."</td>
<td>".$row['created_at']."</td>
</tr>";
}
echo "</table>";
}
else {
echo "0 results";
}
$conn-> close();
?>
</table>
</div>
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JSs -->
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/bootstrap.bundle.min.js"></script>
<script src="js/theme-script.js"></script>
</body>
</html>
【问题讨论】:
-
这段代码没有意义:
$sql = "SELECT * FROM information_schema.tables where table_name = ?"; $result = $conn-> query($sql);您需要通过使用准备好的语句并将值绑定到它来设置 table_name 值。此外,您应该将您的网址更改为view.php?table=' . $row['table_name']以便使用 $_GET 变量轻松检索它 -
注意:
mysqli的面向对象接口明显不那么冗长,使代码更易于阅读和审核,并且不容易与过时的mysql_query接口混淆。在您对程序风格投入过多之前,值得转换一下。示例:$db = new mysqli(…)和$db->prepare("…")程序接口是 PHP 4 时代的产物,当时引入了mysqliAPI,理想情况下不应在新代码中使用。 -
考虑使用development framework 来解决此类问题。这些为您提供了将代码组织到适当的模型、视图和控制器上下文中的模式,并避免最终导致混乱的关注点,HTML、PHP、SQL 和 JavaScript 都混在一起。框架有多种形式,从像 Fat-Free Framework 这样的非常精简到像 Laravel 这样的功能非常齐全,以及介于两者之间的许多地方。
-
为什么不把
folder作为内容表的一列? -
@mario 你是什么意思?