开发者

php mysqli prepared statement using wildcards

I am trying to build this prepared statement:

$sql = "SELECT * FROM entries WHERE";
$sql .= " title LIKE ? OR title LIKE ? OR title LIKE ? OR title LIKE ?";
$sql .= " OR content LIKE ? OR content LIKE ? OR content LIKE ? OR content LIKE ?";

$q = $this->db->prepare($sql);

$one = $this->term;
$two = "%" . $this->term;
$three = $this->term . "%";
$four = "%" . $this->term . "%";

$q->bind_param("ssssssss", $one, $two, $three, $four, $one, $two, $thr开发者_运维知识库ee, $four);
$q->execute();

$this->db is my mysqli connection object

$this->term is a user provided string.

I am not receiving any type of error as from the database. I know the sql statement works, I ran it with a $this->db->query() and it came out fine. When I run it with the prepared statement it comes back with no results. Any suggestions?


To use a wildcard in a prepared statement you need to use CONCAT in your sql statement. The database will take care of concatenating the percent signs onto your search term.

Assuming you want a wildcard at the beginning or end of your search term, your sql should look like:

$sql = "SELECT * FROM entries WHERE title LIKE CONCAT('%', ?, '%') OR content LIKE CONCAT('%', ?, '%')";


I could not get it to work with a prepared statement. I moved to to a mysqli->query() and escaped the user string. Carlos, thanks for the help in fixing my query.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜