php - 如何使用 PHP 将 SQL Select 语句链接到 HTML 按钮
问题描述
我已经使用 PHP 连接到 MySQL 数据库。该数据库是关于书籍的,具有不同的列,例如 ID、标题、作者和价格。我现在正在尝试创建链接“查看表格”、“按标题查看”和“按作者查看”,以便用户可以使用这些链接分别查看我的表格的内容。
我已经创建了三个按钮,但现在我不知道如何让它们分别显示列。下面是我的php代码:
<!DOCTYPE html>
<html>
<head>
<title>Books</title>
<link rel="stylesheet" type="text/css" href="bookstyle.css">
</head>
<body>
<button>View Table</button>
<button>View by Title</button>
<button>View by Author</button>
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Author</th>
<th>Price</th>
</tr>
<?php
$conn = mysqli_connect("localhost", "root", "", "my_book_collection");
// Check connection, if failed show error
if ($conn-> connect_error) {
die("Connection failed:". $conn-> connect_error);
}
$sql = "SELECT id, title, author, price from books";
$result = $conn -> query($sql);
if ($result -> num_rows > 0){
// Output data for each row
while ($row = $result -> fetch_assoc()){
echo "<tr><td>". $row["id"]. "</td><td>". $row["title"]. "</td><td>". $row["author"]. "</td><td>". $row["price"]. "</td></tr>";
}
echo "</table>";
}
else {
echo "0 results";
}$conn-> close();
?>
</table>
</body>
</html>
解决方案
我自己想通了。这可能不是最好的方法,但我所做的是创建 2 个单独的 .php 文件,一个用于作者,一个用于标题。我删除了与作者或标题无关的代码(例如:id 和 price)。所以基本上,我只是为每个表创建了一个新表,然后创建链接以分别访问每个表。每个 .php 文件都有 3 个链接“查看表”“查看作者”“查看标题”。
推荐阅读
- python - 在 Python 中实现变量等待循环
- c# - 为 Net Core 重建的 T4 模板生成器
- xpath - XPath 在字符串位于标签之间时加入字符串
- android - 如何在屏幕外定位 ConstraintLayout 的子项(以便稍后在屏幕上翻译它们)?
- node.js - 如何使用 webpack 4 成功构建带有 pug 模板引擎的 NodeJS 项目
- javascript - JS Cookie 根据用户显示/隐藏表单
- javascript - 使用 .reduce() 对 Javasript 数组进行从宽到长的转换会产生空数组
- angular - pathType.isDirectory 中的错误不是函数
- spreadsheet - 我们如何从电子表格中的文本和数字数据中提取数字?
- python - 根据条件从数据框中创建列表列表