Using wildcards with PHP’s PDO object & prepared statements.

This is a short PHP tutorial on how to use the wildcard character when using prepared statements with the PDO object. In this guide, I will show you how to bind the wildcard and the string you are attempting to match to a given parameter.

The LIKE comparison operator.

As you probably already know, the LIKE comparison operator is often used for simple pattern matching. When using the LIKE comparison operator, developers will often use the wildcard character % like so:

In the example above, I am selecting all users that have the characters “ay” somewhere in their name. By placing a wildcard character at both ends of my string, I am instructing MySQL to return anything with the string “ay” in it, regardless of what characters come before or after it. If I ran the query in question, I would probably receive results such as Blayne, Kayla and Ray.

PDO & Prepared Statements.

If you’re familiar with PHP’s outdated mysql functions, then it is fair to say that you probably used wildcards like so:

However, what if you want to use the PDO object and prepared statements?

Well, it’s actually pretty simple:

A quick overview of the code above:

  1. In this example we are searching for the string “John”.
  2. We created our SELECT statement. As you can see, it contains a simple LIKE comparison operator.
  3. We added the wildcard character to both sides of our $name variable. This means that our $name variable is now “%John%”.
  4. We prepared our statement using the PDO:prepare method.
  5. We binded the value of our $name variable to the name parameter in our SELECT statement.
  6. We executed the statement.
  7. We retrieved our results from the statement that we executed.

As you can see, there is not much of a difference! Hopefully, this helped to clear a few things up!

Facebook Comments