简体   繁体   中英

How to link SQL Select statements to a HTML button using PHP

I have connected to a MySQL database using PHP. The database is about books, which has different columns such as ID, title, author and price. I'm now trying to create links "View Table", "View by title" and "View by Author" so that users can use these links to view the content of my table respectively.

I have created the three buttons, but now I can't figure out how to make them show the columns separately. Below is my php code:

    <!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>

You need to tell your SQL statement what column to order by. You can pass this via the link. eg

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

then in your SQL change to

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

BUT before you implement this, please read up on SQL injection attacks and modify your code to control what value is passed to SQL.

Here are the basics:

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

The variable just needs some sanitation.

Then change your SQL statement to:

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

I figured it out on my own. This is probably not the best way to do it, but what I did was create 2 seperate .php files, one for author and one for titles. I removed the code that didn't relate to author or title (for example: id and price). So basically, I just created a new table for each and then made links to access each table seperately. Each .php file has 3 links "View Table" "View Authors" "View Titles".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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