简体   繁体   中英

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, $three, $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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM