mySqli Bind Parameter LIKE with Wildcard

2019-01-28 21:10发布

问题:

I'm having issues binding the LIKE with Wildcard into my prepared statement in MySQLi. I tried both the following methods below as shown & concat.(updated with @fancyPants input)

  • Is there a way so that I can view my own SQL statement after the binding happens?

  • How do I bind it properly to get the result I want ?

It works without the LIKE statement.

I could only pull out data from using a certain search term. Is there anything wrong with my code?

$str = $_POST["searchstr"];


    if(isset($_POST['submit']))
    {
        $price=$_POST['price'];


        if(!empty($_POST['chkbx']))
        {
            foreach($_POST['chkbx'] as $selected)
            {


                $sql= 'SELECT bookTitle, bookPrice FROM nbc_book WHERE catID LIKE "%'.$selected.'%" AND bookTitle LIKE "%'.$str.'%" AND bookPrice < ?';
                $stmt=mysqli_prepare($con,$sql);
                mysqli_stmt_bind_param($stmt,"i",$price);
                mysqli_stmt_execute($stmt);
                mysqli_stmt_bind_result($stmt, $bookTitle, $bookPrice); 
                while ($stmt->fetch()) {
                     echo $bookTitle.$bookPrice."<br>";
                }
            }
        }
    }

回答1:

$searchStr =  'oracle';
$sql= 'SELECT bookTitle, bookPrice FROM nbc_book WHERE catID LIKE ? AND bookTitle LIKE "%'.$searchStr.'%" AND bookPrice < ?';
$stmt=mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt,"ssi",$selected,$price);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $bookTitle, $bookPrice); 
while ($stmt->fetch()) {
    echo $bookTitle;
}