How can PHP be used to retrieve data from a database based on age criteria?

To retrieve data from a database based on age criteria using PHP, you can use SQL queries with the WHERE clause to filter the results based on the age condition. You can pass the age criteria as a variable in the SQL query to dynamically fetch data based on the specified age range.

<?php
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Define the age criteria
$min_age = 18;
$max_age = 30;

// Fetch data from the database based on age criteria
$sql = "SELECT * FROM users WHERE age >= $min_age AND age <= $max_age";
$result = $conn->query($sql);

// Display the retrieved data
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Name: " . $row["name"]. " - Age: " . $row["age"]. "<br>";
    }
} else {
    echo "No results found";
}

// Close the database connection
$conn->close();
?>