To dynamically retrieve and display levels based on the selected rank from a database in PHP, you'll need to use AJAX to fetch data asynchronously. Below is a simplified example demonstrating the concept:
**index.php:**
```php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rank and Level Dropdown</title>
</head>
<body>
<form>
<label for="rank">Select Rank:</label>
<select id="rank" name="rank" onchange="updateLevelOptions()">
<option value="unranked">Unranked</option>
<option value="silver">Silver</option>
<option value="gold">Gold</option>
</select>
<label for="level">Select Level:</label>
<select id="level" name="level">
<!-- Options will be populated dynamically using JavaScript -->
</select>
</form>
<script>
function updateLevelOptions() {
var rankDropdown = document.getElementById("rank");
var levelDropdown = document.getElementById("level");
var selectedRank = rankDropdown.value;
// Clear existing options
levelDropdown.innerHTML = "";
if (selectedRank !== "unranked") {
// Fetch levels from the server based on the selected rank
fetch('get_levels.php?rank=' + selectedRank)
.then(response => response.json())
.then(levels => {
populateDropdown(levelDropdown, levels);
})
.catch(error => console.error('Error fetching levels:', error));
} else {
// If Unranked is selected, show only "Unranked"
var unrankedOptions = ["Unranked"];
populateDropdown(levelDropdown, unrankedOptions);
}
}
function populateDropdown(dropdown, options) {
for (var i = 0; i < options.length; i++) {
var option = document.createElement("option");
option.text = options[i];
option.value = options[i];
dropdown.add(option);
}
}
</script>
</body>
</html>
```
**get_levels.php:**
```php
<?php
// Assuming you have a database connection
$servername = "your_servername";
$username = "your_username";
$password = "your_password";
$dbname = "your_dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Retrieve levels based on the selected rank
if (isset($_GET['rank'])) {
$selectedRank = $_GET['rank'];
$query = "SELECT level FROM levels WHERE rank = '$selectedRank'";
$result = $conn->query($query);
if ($result->num_rows > 0) {
$levels = [];
while ($row = $result->fetch_assoc()) {
$levels[] = $row['level'];
}
echo json_encode($levels);
} else {
echo json_encode([]);
}
}
$conn->close();
?>
```
This example assumes you have a MySQL database with a table named `levels` containing columns `rank` and `level`. Adjust the database connection details and queries according to your setup. The `get_levels.php` script fetches the levels based on the selected rank and returns them as JSON, which is then processed by the JavaScript in `index.php`.