0

I am trying to write a prepared statement for a very basic search function. Basically, I just need to to return the "title" when the title contains the search term (but may also contain more words than the search term).

I can do this in normal mysqli but not with a prepared statement (which I need for security, right?)

This works but no prepared statement:

$sql = "SELECT title, description FROM quiztime WHERE title LIKE '%".$query."%' OR description LIKE '%".$query."%'";

This doesn't work:

$stmt = $conn->prepare("SELECT user, title FROM quiztime WHERE title LIKE %?%");

I get in log: PHP Fatal error: Uncaught Error:

So how can I make that into a prepared statement? Many thanks!

T C
  • 41
  • 1
  • 7

1 Answers1

0

You must use concatenation:

$stmt = $conn->prepare("SELECT user, title FROM quiztime WHERE title LIKE concat('%', ?, '%')");
forpas
  • 160,666
  • 10
  • 38
  • 76
  • That returns every user and title from the database...but at least it returns something, which is an improvement! – T C Aug 31 '19 at 22:06
  • Did you try it with concat()? If so what do you pass as argument? – forpas Aug 31 '19 at 22:07
  • 1
    This worked! `$likeVar = "%" . $query. "%";` `$stmt = $mysqli->prepare("SELECT user, title FROM quiztime WHERE title LIKE ?");` `$stmt->bind_param("s", $likeVar);` – T C Aug 31 '19 at 22:15
  • So you did the concatenation and pass this as a parameter. The code in the answer does the concatenation if you pass the actual parameter without wildcards. – forpas Aug 31 '19 at 22:18
  • yeah, I think I get this! Learning curve...Thanks for your help! – T C Aug 31 '19 at 22:25