首页 > 解决方案 > 如何使用 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>

标签: phphtmlmysqldatabasephpmyadmin

解决方案


我自己想通了。这可能不是最好的方法,但我所做的是创建 2 个单独的 .php 文件,一个用于作者,一个用于标题。我删除了与作者或标题无关的代码(例如:id 和 price)。所以基本上,我只是为每个表创建了一个新表,然后创建链接以分别访问每个表。每个 .php 文件都有 3 个链接“查看表”“查看作者”“查看标题”。


推荐阅读