I have been trying to use LIKE inside a prepared statement, but php won't execute the statement because of a syntax error due to the use of the wildcard %.
Here is the code
$query = pg_prepare($conn, "MyStatement",
'SELECT "Query" from "MyTable"
WHERE "Query" LIKE $1%
ORDER BY "MyColumn" DESC;');
$result = pg_execute($conn, "MyStatement", array($my_param));
The thing is that php shows me a warning in the second line claiming a syntax error.
The PostgreSQL LIKE operator is used to match text values against a pattern using wildcards. If the search expression can be matched to the pattern expression, the LIKE operator will return true, which is 1. The percent sign represents zero, one, or multiple numbers or characters.
PostgreSQL provides you with two wildcards: Percent sign ( % ) matches any sequence of zero or more characters. Underscore sign ( _ ) matches any single character.
Example 1: Here we will make a query to find the customer in the “customer” table by looking at the “first_name” column to see if there is any value that doesn't begin with “K” using the NOT LIKE operator in our sample database. SELECT first_name, last_name FROM customer WHERE first_name NOT LIKE 'K%';
The keyword ILIKE can be used instead of LIKE to make the match case insensitive according to the active locale. This is not in the SQL standard but is a PostgreSQL extension. The operator ~~ is equivalent to LIKE , and ~~* corresponds to ILIKE .
I've had the same issue binding parameters using PDO adapters. The solution is to pass the "%" in with the variable:
$query = pg_prepare($conn, "MyStatement",
'SELECT "Query" from "MyTable"
WHERE "Query" LIKE $1
ORDER BY "MyColumn" DESC;');
$result = pg_execute($conn, "MyStatement", array($my_param."%"));
If you need
...LIKE '%param%' ...
Then your query would be:
$result = pg_execute($conn, "MyStatement", array("%".$my_param."%"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With