How can PHP beginners effectively implement user filtering based on specific criteria in a database?
To implement user filtering based on specific criteria in a database, PHP beginners can use SQL queries with conditions to retrieve only the desired user data. By using the WHERE clause in SQL queries, users can be filtered based on specific criteria such as age, gender, or any other relevant information stored in the database.
// Connect 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 criteria for filtering
$criteria = "age > 18 AND gender = 'female'";
// Select users based on the criteria
$sql = "SELECT * FROM users WHERE $criteria";
$result = $conn->query($sql);
// Output the filtered users
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"]. " - Age: " . $row["age"]. " - Gender: " . $row["gender"]. "<br>";
}
} else {
echo "No users found based on the criteria.";
}
// Close the connection
$conn->close();
Keywords
Related Questions
- When should fetchAll be used over fetch in PDO for retrieving database results in PHP?
- What is the significance of the error message "Warning: preg_match() expects parameter 2 to be string, resource given" in PHP?
- How can the error message "mysqli_query() expects at least 2 parameters, 1 given" be resolved in PHP code?