如何使用PHP将SQL Select语句链接到HTML按钮

问题描述 投票:1回答:2

我已经使用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>
php html mysql database phpmyadmin
2个回答
1
投票

您需要告诉您的SQL语句要按哪个列排序。您可以通过链接传递此信息。例如

<th><a href="?order=author">Author</a></th>

然后在你的SQL中更改为

'SELECT id, title, author, price FROM books ORDER BY '.$_GET['order'].' ASC'

但在实现之前,请阅读SQL注入攻击并修改代码以控制传递给SQL的值。

以下是基础知识:

if ($_GET['order'] == 'author') $order = 'author';
if ($_GET['title'] == 'title') $order = 'title';
etc.

变量只需要一些卫生设施。

然后将您的SQL语句更改为:

'SELECT id, title, author, price FROM books ORDER BY '.$order.' ASC'

1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.