How can PHP be used to display topic headings from a database and show corresponding descriptions upon user interaction?
To display topic headings from a database and show corresponding descriptions upon user interaction, you can use PHP to retrieve the data from the database and dynamically display the descriptions based on user interaction. This can be achieved by using AJAX to fetch the description data without refreshing the page.
<?php
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "your_database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Retrieve topic headings from database
$sql = "SELECT * FROM topics";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<h2 class='topic' data-id='" . $row['id'] . "'>" . $row['heading'] . "</h2>";
echo "<p class='description' data-id='" . $row['id'] . "' style='display:none;'>" . $row['description'] . "</p>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Keywords
Related Questions
- In PHP, what considerations should be taken into account when determining the maximum number of stops allowed in a race strategy calculation?
- How can beginners understand and utilize the "->" symbol effectively?
- Are there any best practices or recommended alternatives to using ftp_connect for checking if an FTP server is running?