Skip to content
PHP Logo

How can the SQL keyword "WHERE" be used in PHP to filter results based on a specific value?

When using SQL queries in PHP to retrieve data from a database, the WHERE keyword can be used to filter results based on a specific value or condition. This allows us to narrow down the results returned by the query to only those that meet the specified criteria. By including the WHERE keyword followed by the condition we want to filter by, we can ensure that only relevant data is retrieved from the database.

php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

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

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

// SQL query with WHERE clause to filter results based on a specific value
$sql = "SELECT * FROM users WHERE age > 18";
$result = $conn->query($sql);

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

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