PHP MySQL WHERE: How to Filter Data in MySQL

Filtering data is a big part of getting the right information to show up. That is where the WHERE clause in MySQL shines. It helps you narrow down your results to exactly what you need. If you are using PHP to interact with a MySQL database, knowing how to work with WHERE will make your applications more dynamic.

In this article, you will learn everything about the WHERE clause, step-by-step, in easy.

What is the WHERE Clause in MySQL?

The WHERE clause acts as a filter to narrow down your database queries. Instead of pulling all the data from a table, it allows you to set conditions and fetch only the rows that match those conditions.

For example, if you want to get all users aged over 12 from a users table, the WHERE clause makes it possible.

Here is its syntax:

SELECT column1, column2 FROM table_name WHERE condition;

So, in this line, we have 3 parts which are building the query from database using SQL:

  • SELECT: Choose which columns you want to retrieve.
  • FROM: This specifies from which the table fetches the data.
  • WHERE: Adds the condition to filter results.

Here is a quick example:

SELECT * FROM users WHERE age > 12;

This query fetches all rows where the age column has a value greater than 12.

That was for SQL, let’s see how we can do that using PDO and mysqli in PHP.

Using WHERE with mysqli in PHP

mysqli is a common way to interact with MySQL databases. Let us look at two methods to use the WHERE clause with mysqli: procedural and object-oriented.

Procedural Method for Queries with WHERE

$sqlconn = mysqli_connect("localhost", "username", "password", "database");

if (!$sqlconn ) {
    die("Error in SQL Connection: " . mysqli_connect_error());
}

$sql_qr = "SELECT * FROM users WHERE age > 33";
$result = mysqli_query($sqlconn , $sql_qr);

if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        echo "Full Name:" . $row["name"] . "<br>";
    }
} else {
    echo "No results found.";
}

mysqli_close($sqlconn );

Object-Oriented Method for Queries with WHERE

$connection = new mysqli("localhost", "user", "pass", "db");

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

$queryString = "SELECT * FROM users WHERE age > 33";
$queryResult = $connection->query($queryString);

if ($queryResult->num_rows > 0) {
    while ($data = $queryResult->fetch_assoc()) {
        echo "Name: " . $data["name"] . "
";
    }
} else {
    echo "No data found.";
}

$connection->close();

Let’s see another example using PDO in PHP.

Using PDO with WHERE Clause

PDO (PHP Data Objects) provides an alternative for interacting with MySQL. It is highly secure and supports prepared statements by default.

Here is an example:

try {
    $sqlconn = new PDO("mysql:host=localhost;dbname=name_of_database", "db_username", "db_password");
    $sqlconn ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $sqlconn ->prepare("SELECT * FROM users WHERE age > ?");
    $stmt->execute([12]);

    $sqlresults = $stmt->fetchAll();
    foreach ( $sqlresults as $row) {
        echo "Full Name: " . $row["name"] . "<br>";
    }
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$sqlconn = null;

Prepared statements are hands down the most reliable way to keep your queries secure. They prevent SQL injection and handle data more safely. Here is an example with PDO:

$stmt = $sqlconn ->prepare("SELECT * FROM users WHERE name = ?");
$stmt->execute(['John']);

So, there are many ways to allow you to filter records, let’s see each one in detail in the following section.

Using Operators in Filters

Fetching results with WHERE is all about using the right condition. For example:

  • Use = for exact matches.
  • Use > or < for ranges.
  • Combine multiple conditions with AND or OR.

Comparison operators help you build powerful queries. Here are a few examples:

  • Equal to (=): WHERE age = 25
  • Not equal to (!=): WHERE status != 'inactive'
  • Greater than (>): WHERE age > 30
  • Less than (<): WHERE age < 12

Logical operators let you combine multiple conditions:

  • AND: All conditions must be true.
  • OR: At least one condition must be true.
  • NOT: Excludes a condition.

The LIKE operator is great for searching patterns. Use % as a wildcard:

  • WHERE name LIKE '%son' (Names ending with “son”).
  • WHERE name LIKE 'J%' (Names starting with “J”).

To find rows with missing data, use:

  • IS NOT NULL: Finds rows where a column has a value.
  • IS NULL: Finds rows where a column is NULL.

Here is an example for each one:

// => Find rows with missing data
SELECT * FROM users WHERE last_login IS NULL;

// => Find by query from SQL using LIKE operator (Searching Pattern)
SELECT * FROM users WHERE name LIKE '%son';

// => Logical operator (AND)
SELECT * FROM users WHERE age > 12 AND status = 'active';

// => Filter by not equal operator
SELECT * FROM users WHERE status != 'inactive';

Let’s summarize it.

Wrapping Up

The WHERE clause is a handy way to filter and manage your database queries when using MySQL with PHP. It helps you filter data, create dynamic queries, and ensure your applications fetch exactly what they need.

Similar Reads

PHP NOT ( ! ) Operator: A Comprehensive Guide

The NOT operator in PHP (!) provides the reverse of whatever truth value is given by a certain expression. It’s…

PHP Variable Basics: Everything You Need to Know

Think about the PHP variable as little storage boxes holding your data, whether it is a number, a word, or…

PHP if-elseif Statement: ‘elseif’ versus ‘else if’

PHP’s if-elseif statement is a fundamental construct that allows developers to control the flow of their code based on different conditions. In…

PHP Global Variables & Superglobals: A Complete Guide

Variables in PHP are general elements used for data storage and other manipulations. Global variables belong to a particular category…

Static Method in PHP: How They Work in Classes

PHP static method lets you call functions without an object. In this article, we will cover the following topics: The…

PHP Spread Operator: Understand How (…) Syntax Works

Before the spread operator, PHP developers had to pass array items to a function using extra steps. They often had…

Inheritance in PHP: Share Code from Class to Class & Examples

PHP developers copied and pasted code across multiple files before inheritance came, which made updates difficult. They updated functions in…

PHP fwrite: How to Write Data to Files in PHP

actions, store settings, or even create log files for debugging. That’s where PHP fwrite comes in. It writes data to…

How to Delete Data in PHP MySQL

In this tutorials, we are going to explain the PHP MySQL Delete Data process with a simple, unique guide. By…

PHP $_SERVER: Basics and Examples

PHP $_SERVER is a superglobal. It’s a predefined variable containing information about your server, client, and request environment. As a…

Previous Article

How to Select Data Using PHP and MySQL?

Next Article

PHP Prepared Statements in MySQL: Preventing SQL Injection

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.