How can one add a WHERE clause to a SQL query in PHP to filter results based on specific conditions?

To add a WHERE clause to a SQL query in PHP, you can simply append the condition to the query string. This allows you to filter results based on specific conditions such as a particular value in a column. Make sure to properly sanitize user inputs to prevent SQL injection attacks.

// Establish a connection to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Define the condition for the WHERE clause
$condition = "column_name = 'specific_value'";

// Build the SQL query with the WHERE clause
$query = "SELECT * FROM my_table WHERE $condition";

// Prepare and execute the query
$statement = $pdo->prepare($query);
$statement->execute();

// Fetch the results
$results = $statement->fetchAll(PDO::FETCH_ASSOC);

// Loop through the results and do something with them
foreach ($results as $result) {
    // Do something with each row
}