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'] . "%'");
3
  • $par="%" . $_GET['search'] . "%" ,$stmt->bind_param('s',$par); Commented Dec 12, 2018 at 8: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? Commented Dec 12, 2018 at 17:47
  • Does this answer your question? Correct way to use LIKE '%{$var}%' with prepared statements? [mysqli] Commented Jan 19, 2020 at 0:26

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.