I am trying to bind a parameter in a LIKE statement in SQL using mysqli like so:
$title = $_POST['title'];
$author = $_POST['author'];
$isbn = $_POST['isbn'];
$q = 'SELECT * from `books`';
if (!isblank($title) || !isblank($author) || !isblank($isbn)) {
$q .= ' WHERE 1 = 1';
}
if (!isblank($title)) {
$q .= ' AND `title` LIKE "%?%"';
}
if (!isblank($author)) {
$q .= ' AND `author` LIKE "%?%"';
}
if (!isblank($isbn)) {
$q .= ' AND `isbn` = ?';
}
echo $q;
if ($statement = $db->prepare($q)) {
if (!isblank($title) && !isblank($author) && !isblank($isbn)) {
$statement->bind_param('sss', $title, $author, $isbn);
} else if (!isblank($title) && !isblank($author)) {
$statement->bind_param('ss', $title, $author);
} else if (!isblank($title) && !isblank($isbn)) {
$statement->bind_param('ss', $title, $isbn);
} else if (!isblank($author) && !isblank($isbn)) {
$statement->bind_param('ss', $author, $isbn);
} else if (!isblank($title)) {
$statement->bind_param('s', $title);
} else if (!isblank($author)) {
$statement->bind_param('s', $author);
} else {
$statement->bind_param('s', $isbn);
}
if ($statement->execute()) {
$statement->bind_result($returned_book); // hello carlo how are you today
while ($statement->fetch()) {
echo var_dump($returned_book);
}
}
}
The problem is that mysqli will states that there are not enough parameters to bind to because the ? is in the string. If I get rid of the quotes ($q .= ' ANDtitleLIKE %?%';) the parameter binds correctly but the SQL syntax is invalid. How can I bind to this LIKE query?
ifconditions where you build the query. Then you simply send that array to theexecutemethod. No conditional binding necessary although it would be possible using named parameters and repeating the initial conditions. A possible solution here would be to remove the quotes and%'s and add the%'s to your string values when you bind.