繁体   English   中英

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

[英]How to link SQL Select statements to a HTML button using PHP

我已经使用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>

您需要告诉您的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'

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM