Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LIKE wildcards inside pg_prepare

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.

like image 976
danielrvt Avatar asked May 16 '12 22:05

danielrvt


People also ask

How do I use like keyword in PostgreSQL?

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.

How do I do a wildcard search in PostgreSQL?

PostgreSQL provides you with two wildcards: Percent sign ( % ) matches any sequence of zero or more characters. Underscore sign ( _ ) matches any single character.

How do I write not like in PostgreSQL?

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%';

What is Ilike in PostgreSQL?

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 .


1 Answers

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."%"));
like image 59
ContextSwitch Avatar answered Sep 22 '22 16:09

ContextSwitch