php - mysql to html table where the user can select a single listing
is there a way for me to create a button that will pass the data from a single row of table into a new page. The table was created from data queried from mysql database.
id | first name | last name | edit | |
---|---|---|---|---|
1 | John | Doe | johndoe@gmail.com | Btn |
2 | James | Doe | jamesdoe@gmail.com | Btn |
Answer
Solution:
Short answer: Yes, there is a way.
Here 's a short example.
<a href="edit.php?id=<?= htmlspecialchars($row['id']) ?>" class="css-button">Details</a>
This is a html a-element. Its href attribute links to a file edit.php
in your current directory. The link takes a parameter called "id" which is the primary key of your rowset from the database. You can style this a-element with css so it can look like everything. In the best case you style it as a button.
<?php
// edit.php content
$id = intval($_GET['id']);
$sql = "SELECT id, username, bla, blubb FROM user WHERE id = :id";
$pdo = new PDO(...); // new pdo instance with database credentials
$stmt = $pdo->prepare($sql);
$stmt->execute(['id' => $id]);
$row = $stmt->fetch();
// continue with additional processing ...
The above shown code takes the id parameter and validates it as an integer value. Then you select the rowset by the primary key (id parameter) with the native php class PDO
, respective PDOStatement
. The only thing you have to do on your own is checking, if the database result from the fetch method is false
. That 's all.