How can you dynamically generate links in PHP based on database content and handle the corresponding data retrieval when the links are clicked?
To dynamically generate links in PHP based on database content, you can query the database to retrieve the necessary information and then loop through the results to create the links. When a link is clicked, you can pass a unique identifier as a parameter in the URL which can then be used to retrieve the corresponding data from the database.
<?php
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query database to retrieve data
$sql = "SELECT id, title FROM articles";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "<a href='article.php?id=" . $row["id"] . "'>" . $row["title"] . "</a><br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Related Questions
- How can a custom DB class be implemented in PHP to improve code structure and database connection management?
- Are there any best practices for efficiently storing and manipulating data extracted from a non-standard file format in PHP?
- What best practices should be followed when using MySQL queries in PHP scripts to prevent server performance issues?