When working with queries in WordPress, it’s always best to prepare the query before running it; however, if you happen to be interfacing with a third-party API or working with another variant of SQL (like Transact-SQL), then things may work a little differently.
The TL;DR of all of this is that handling sprintf and LIKE in T-SQL needs some strategic handling. And the code sample in the next section should provide all you need.
sprintf and LIKE in SQL
Some background on the problem at hand:
Say that you’re working on a project in which you’re making calls to a third-party API and the said API uses T-SQL to interface with its database.
Further, let’s say that you want to retrieve records that have a segment of the string to be queried (you know, a LIKE, clause). The caveat is that you can’t use the standard prepare function as provided by WordPress so you opt to use sprintf to help sanitize the incoming information.
Since sprintf uses %s
for strings and since you’re using a LIKE clause which also requires %
, how does one handle the case of using both?
Here’s an example of how it may work for you:
Of course, I still think using some type of escaping on the $name
argument but there are a number of different ways to do this and it’s beyond the point of this post.
In short, prefix and suffix the %s
with %%
and you should be good to go.