0

I am trying to implement MySQL full text search in my app.

But I get an empty array as a result only if I use a prepared statement. If I simply put php variable in SQL query it works just fine but it is not what I want.

This returns few records as it should:

try { $sql = /** @lang mysql */ "SELECT *, MATCH (first_name, last_name, email, username) AGAINST (('$string*') IN BOOLEAN MODE) AS score FROM customer p WHERE MATCH (first_name, last_name, email, username) AGAINST (('$string*') IN BOOLEAN MODE) ORDER BY score DESC LIMIT 100; "; $stmt = $conn->prepare($sql); $stmt->execute(); }catch (\Exception $e){

Following code returns [ ]:

try { $sql = /** @lang mysql */ "SELECT *, MATCH (first_name, last_name, email, username) AGAINST ((':string*') IN BOOLEAN MODE) AS score FROM customer p WHERE MATCH (first_name, last_name, email, username) AGAINST ((':string*') IN BOOLEAN MODE) ORDER BY score DESC LIMIT 100; "; $stmt = $conn->prepare($sql); $stmt->execute(['string' => $string]);

Query like following:

SELECT *, MATCH (first_name, last_name, email, username) AGAINST ((:string*) IN BOOLEAN MODE) AS score FROM customer p WHERE MATCH (first_name, last_name, email, username) AGAINST ((:string*) IN BOOLEAN MODE) ORDER BY score DESC LIMIT 100;

Results in following error:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') IN BOOLEAN MODE) AS score FROM customer p WHE' at line 2

I expect the second query to work the same as the first one.

As much as I understand There is some "trick" of rule of writing this which I do not know and/or cannot find. Please tell me:

How to use Full-text search with the prepared statement. What is the syntax?

some_guy
  • 390
  • 2
  • 14
  • Regarding 'mark as duplicate' mark: People thanks for directing me somewhere. But having those single quotes was the only way to make it work. Otherwise, there is an exception about asterisk or closed bracket like unexpecting character. Question edited. – some_guy Feb 09 '19 at 18:33
  • 1
    If you search the linked answer for "prepared statements", you will find that the placeholders are not enclosed. The `*` should be "injected" when you bind the parameter. Try `AGAINST ((:string) IN BOOLEAN MODE)` and `$stmt->execute(['string' => $string . '*']);` – Paul Spiegel Feb 09 '19 at 18:41
  • Guess I was too stupid to realize that. Thanks, man! – some_guy Feb 09 '19 at 18:42

0 Answers0