MySQL WHERE Clause

PHP MySQL WHERE Clause

The WHERE clause is used in SQL to filter records and fetch only those rows that meet a specified condition.

When working with PHP and MySQL, you use the WHERE clause in a SQL query to retrieve specific data from a table based on certain criteria.

Syntax

SELECT column1, column2, ...
FROM table_name
WHERE condition;

Example Database Table: students

id name age grade
1 John 18 A
2 Alice 17 B
3 Michael 18 A
4 Jennifer 19 C

PHP Example: Select students with grade 'A'

<?php
// Database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "school";

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

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

// SQL SELECT with WHERE clause
$sql = "SELECT id, name, grade FROM students WHERE grade = 'A'";
$result = $conn->query($sql);

// Output data
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Grade: " . $row["grade"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>

Key Points:

  • Always validate and sanitize user input before using it in a WHERE clause to prevent SQL injection.

  • Use quotes for string values in the condition (WHERE name = 'John'), but not for numeric values (WHERE age = 18).

  • You can use logical operators like AND, OR, and NOT for more complex conditions.

More Examples

1. Multiple Conditions

SELECT * FROM students WHERE grade = 'A' AND age = 18;

2. Using LIKE

SELECT * FROM students WHERE name LIKE 'J%';

3. Using IN

SELECT * FROM students WHERE grade IN ('A', 'B');