0

I'm getting this error:

Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement

code:

$stmt = $sql->prepare("SELECT name, site, message, `when` FROM messages WHERE message LIKE '%?%'");
$stmt->bind_param('s', $_GET['search']);
$stmt->execute();
$result = $stmt->get_result();

I'm trying to get the user input into the prepared statement.

This code works fine but is insecure against SQL injections:

$result = $sql->query("SELECT name, site, message, `when` FROM messages WHERE message LIKE '%" . $_GET['search'] . "%'");
Dharman
  • 30,962
  • 25
  • 85
  • 135
KVCODES
  • 3
  • 3
  • `$par="%" . $_GET['search'] . "%" ,$stmt->bind_param('s',$par);` – Shubham Dixit Dec 12 '18 at 08:23
  • When you use a parameter placeholder `?`, don't put it inside the string delimiters. A question mark inside a string counts as a normal question mark character. If it were a parameter placeholder, how could you ever use a normal question mark in a string? – Bill Karwin Dec 12 '18 at 17:47
  • Does this answer your question? [Correct way to use LIKE '%{$var}%' with prepared statements? \[mysqli\]](https://stackoverflow.com/questions/28385145/correct-way-to-use-like-var-with-prepared-statements-mysqli) – Dharman Jan 19 '20 at 00:26

1 Answers1

1

When using LIKE in a prepared statement, it's a little bit different. You should add the % to the parameter before binding it to the statement.

Try something like below:

$param = "%{$_GET['search']}%";
$stmt = $sql->prepare("SELECT name, site, message, `when` FROM messages WHERE message LIKE ?");
$stmt->bind_param('s', $param);
$stmt->execute();
$result = $stmt->get_result();
rpm192
  • 2,630
  • 3
  • 20
  • 38