← Back to Chapters

MySQL SELECT With WHERE Clause

? MySQL SELECT With WHERE Clause

? Quick Overview

The WHERE clause in MySQL is used to filter records that meet a specific condition. It is commonly used with SELECT queries in PHP-MySQL applications to retrieve only the required data.

? Key Concepts

  • Filters rows based on conditions
  • Used with comparison and logical operators
  • Essential for dynamic PHP database queries

⚡ Syntax / Theory

? View Code Example
// Basic SELECT query with WHERE condition
SELECT column1, column2
FROM table_name
WHERE condition;

? Example 1: Filter Records

? View Code Example
// Fetch users older than 30
SELECT * FROM users
WHERE age > 30;

? Explanation

Only users whose age value is greater than 30 will be returned from the database.

? Example 2: WHERE with AND / OR

? View Code Example
// Multiple conditions using AND
SELECT * FROM users
WHERE age > 30 AND city = 'New York';
? View Code Example
// Either condition using OR
SELECT * FROM users
WHERE age > 30 OR city = 'New York';

? Example 3: WHERE with LIKE

? View Code Example
// Pattern matching using LIKE
SELECT * FROM users
WHERE username LIKE 'J%';

?️ Example 4: WHERE with IN

? View Code Example
// Filter using multiple values
SELECT * FROM users
WHERE city IN ('New York','Los Angeles');

? Interactive Understanding

Imagine a PHP login page that only fetches users with a matching email. The WHERE clause makes this possible efficiently.

? Use Cases

  • User authentication in PHP
  • Filtering search results
  • Admin dashboards and reports
  • Dynamic API responses

✅ Tips & Best Practices

  • Always sanitize user input in PHP
  • Use indexed columns for faster WHERE queries
  • Prefer prepared statements for security

? Try It Yourself

  • Select users older than 25 from Los Angeles
  • Find emails containing the word "example"
  • Combine AND and OR for advanced filters