[英]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.